1.将表单序列化为 JSON-Object
$.fn.serializeObject = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
2.定义内容类型为application/json的AJAX请求
$.ajaxSetup({
contentType: "application/json; charset=utf-8"
});
function request(path, params, method) {
method = method || "POST";
$.ajax({
url: path,
type: method,
data: params,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
//do something
},
error: function (xhr, ajaxOptions, thrownError) {
//do something
}
});
}
3.表单提交后发送数据
$(function() {
var url = "/api/route";
$('form').submit(function() {
var json = JSON.stringify($('form').serializeObject());
request(url, json);
return false;
});
});