將表單內容轉化成json字串,並通過ajax提交!
阿新 • • 發佈:2019-01-03
1.JQuery的自定義方法,直接寫個js檔案放到裡邊,用的時候引一下就可以。
(function($) {
$.fn.extend({
serializeObject : function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
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;
}
});
})(jQuery)
2.引入JQuery的包然後直接用下邊的ajax提交就行。
var url = "url";
$.ajax({
url : url,
type : 'post',
data:$.toJSON($('#form表單的id').serializeObject()),
contentType : 'application/json;charset=UTF-8',
success : function(result) {
alert("成功!");
},
error : function() {
alert("失敗!");
}
});
3.更新的
$.ajax({
url : url,
type : 'put',
data:$.toJSON($('#form表單的id').serializeObject()),
contentType : 'application/json;charset=UTF-8',
success : function(result) {
alert("成功!");
},
error : function() {
alert("失敗!");
}
});
4.刪除的
url中最後為刪除id
$.ajax({
url : url,
type : 'get',
success : function(result) {
alert("成功!");
},
error : function() {
alert("失敗!");
}
});