有时候仅仅只用到异步提交就加载第三方js库是不明智的,纯js异步提交,javascript自写ajax方法,不依赖其他插件,调用方便。
demo.html源码:
<!DOCTYPE html>
<html lang="zh-cn">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
<title>纯js异步提交javascript自写ajax方法</title>
<meta name="keywords" content="纯js异步提交,javascript自写ajax方法">
<meta name="description" content="纯js异步提交javascript自写ajax方法,不依赖其他插件,调用方便。">
<style>
</style>
</head>
<div class="box">
<input type="text" id="param_id" /><br><br>
<input type="text" id="param_name" /><br><br>
<input type="file" id="param_file" /><br><br>
<input type="hidden" id="param_hidden" />
<button onclick="sub_fun();">提交</button>
</div>
</body>
<script type="text/javascript">
* js异步提交自写ajax方法
var zhlC_ajax = {
get: function(url,fn,s,e){
var xhr=new XMLHttpRequest();
xhr.open('GET',url,false);
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200 || xhr.status==304){
console.log(xhr.responseText);
s(xhr.responseText);
}else{
e(xhr.responseText);
xhr.send();
post: function(url,data,s,e){
var xhr = new XMLHttpRequest();
xhr.open('POST',url);
xhr.onreadystatechange=function(){
if (xhr.readyState==4){
if (xhr.status==200 || xhr.status==304){
s(xhr.responseText);
}else if(xhr.status>=400){
e(xhr.responseText);
xhr.send(data);
* 选择文件获取文件base64编码
window.onload = function(){
var imagesfile = document.getElementById("param_file");
imagesfile.onchange = function () {
var file = imagesfile.files[0];
if (file.size > 10 * 1024 * 1024) {
alert("上传文件必须 < 10Mb!");
return false;
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader);
var base64 = reader.result;
document.getElementById("param_hidden").value = base64;
* 数据提交方法
function sub_fun(){
var url = 'test.php';
var id = document.getElementById('param_id').value;
var name = document.getElementById('param_name').value;
var base64 = document.getElementById("param_hidden").value;
console.log(id);console.log(base64);
if(!id || !name || !base64){
alert('参数不能为空');return;
var uploadimg = base64File(base64);
var formData = new FormData();
formData.append("id", id);
formData.append("name", name);
formData.append("uploadimg", uploadimg);
zhlC_ajax.post(url,formData,function(data){
console.log('请求成功');
var newDate = JSON.parse(data);
if(newDate.code == 10000){
alert('成功');
}else{
alert('失败'+newDate.msg);
},function(data){
console.log('请求失败');
alert('网络异常,稍后再试');
* 将图片Base64数据转成文件
function base64File(base64Data) {
var arr = base64Data.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
return new Blob([u8arr], { type: mime });
</script>
</html>
服务端接收数据以php为例:
<?php
$result = array('code'=>'40000','data'=>array());
$id = isset($_REQUEST['id']) ? $_REQUEST['id'] : '';
$name = isset($_REQUEST['name']) ? $_REQUEST['name'] : '';
$result['data']['id'] = $id;
$result['data']['name'] = $name;
if(!isset($_FILES)){
echo json_encode($result);exit;
$file = $_FILES['uploadimg']['tmp_name'];
$path = './upload/';
if(!file_exists($path)){
mkdir($path,0777);
$newname = time().rand(100,999);
$upfile = $path.$newname.'.jpg';
if(move_uploaded_file($file,$upfile)){
$suf = getFileType($upfile);
$updatefile = $path.$newname.'.'.$suf;
$re = rename($upfile, $updatefile);
if($re){
$upfile = $updatefile;
$result['code'] = 10000;
$result['data']['filepath'] = substr($upfile, 1);
echo json_encode($result);exit;
* 判断文件类型
function getFileType($file){
$filehead = fopen($file,'r');
$bin = fread($filehead, 2);
fclose($filehead);
$data = unpack('C2chars', $bin);
$type_code = intval($data['chars1'].$data['chars2']);
switch ($type_code) {
case 7790:
$fileType = 'exe';
break;
case 7784:
$fileType = 'midi';
break;
case 8075:
$fileType = 'zip';
break;
case 8297:
$fileType = 'rar';
break;
case 255216:
$fileType = 'jpg';
break;
case 7173:
$fileType = 'gif';
break;
case 6677:
$fileType = 'bmp';
break;
case 13780:
$fileType = 'png';
break;
default:
$fileType = '';
break;
return $fileType;