標題:AJAX送出POST/GET/FILE並取得JSON資訊
HTML (index.html):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-TW" xml:lang="zh-TW">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Send Post</title>
<script type="text/javascript">
var sendPost = function() {
this.current = null;
this.queue = [];
};
sendPost.prototype.request = function(q) {
var self = this;
var query = [];
var formdata = new FormData(document.createElement('form'));
for(key in q.params) {
switch(q.params[key].constructor) {
case Number:
formdata.append(key, q.params[key]);
break;
case String:
formdata.append(key, q.params[key]);
break;
case Array:
for(var i=0;i<q.params[key].length;i++) {
formdata.append(key, q.params[key][i]);
}
break;
default:
var type = q.params[key].getAttribute("type");
if(type == 'file') {
for(var i=0;i<q.params[key].files.length;i++) {
formdata.append(key, q.params[key].files[i]);
}
} else if(type=='password'||type=='text'||type=='hidden') {
formdata.append(key, q.params[key].value);
}
break;
}
}
var xobj = new XMLHttpRequest();
xobj.overrideMimeType('application/json');
xobj.open('POST', q.url, true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == '200') {
self.current.load(JSON.parse(xobj.responseText));
self.action();
}
};
this.queue.push({
xobj : xobj,
formdata : formdata,
load : q.load
});
if(!this.current) this.action();
};
sendPost.prototype.action = function() {
this.current = null;
if(this.queue.length) {
this.current = this.queue.shift();
this.current.xobj.send(this.current.formdata);
}
};
window.onload = function() {
document.getElementById('btn').onclick = function() {
var mySendPost = new sendPost();
mySendPost.request({
url : '/test?method=work',
params : {
'file' : document.getElementById('myfile'),
'name' : document.getElementById('myname'),
'password' : document.getElementById('mypassword'),
'hidden' : document.getElementById('myhidden'),
'str' : 'Hello',
'num1' : 20,
'num2' : new Array(30, 40)
},
load : function(data) {
document.getElementById('output').innerHTML = JSON.stringify(data, null, 2);
}
});
};
};
</script>
</head>
<body>
<input type="file" id="myfile" multiple="multiple" /><br />
<input type="text" id="myname" value="QQBoxy" /><br />
<input type="password" id="mypassword" value="abcd1234" /><br />
<input type="hidden" id="myhidden" value="HideBoxy" />
<button id="btn">Button</button><br />
<pre id="output"></pre>
</body>
</html>
Node.js (main.js):
var express = require('./node_modules/express'),
multiparty = require('./node_modules/multiparty'),
multipart = require('./node_modules/connect-multiparty');
var port = 1337;
var app = express();
var multipartMiddleware = multipart();
app.listen(port);
app.use('/', express.static(__dirname + '/html/'));
app.post('/test', multipartMiddleware, function(req, res) {
res.set('Content-Type', 'application/json;charset=utf-8');
var json = {
'get' : req.query,
'post' : req.body,
'file' : req.files
};
//console.log(JSON.stringify(json, null, 2)); //測試用
res.send(JSON.stringify(json, null, 2));
});
console.log("Start express server on port %s", port);
範例結果:
說明:
使用FormData方式傳送GET、POST、FILE資訊,
並且建立簡單Node.js伺服器傳回之JSON資訊進行測試,
關於Node.js接收檔案的方法請參考
這篇。
Google Chrome 34.0.1847.131 m、Firefox 27.0.1、IE11 測試可正常執行。