使用 JQuery 通过 Ajax 以 Json 格式发送表单数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20227789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Send Post Form Data in Json Format Via Ajax With JQuery
提问by Spittal
as the title says I'm sending some post data via ajax. but I keep on getting errors, can anyone take a look at the code and explain why my ajax call keeps failing?
正如标题所说,我正在通过 ajax 发送一些帖子数据。但我不断收到错误,谁能看看代码并解释为什么我的 ajax 调用总是失败?
submitForm(jQuery('#priceCalc'), {name: 'thingdoto', value: "true"});
function submitForm(form, data) {
var postData = form.serializeArray(),
formURL = form.attr("action");
postData.push(data);
console.log(postData);
jQuery.ajax({
url : formURL,
type: 'POST',
dataType : "json",
data: postData,
success:function(data)
{
jQuery('#priceTotal').html(data);
},
error: function()
{
jQuery('#priceTotal').html('error');
}
});
}
EDIT: The ajax call returns the error, so it's just not succeeding. Don't know why.
编辑:ajax 调用返回错误,所以它没有成功。不知道为什么。
回答by Philip
You're sending data as an array, not a JSON string.
您将数据作为数组发送,而不是 JSON 字符串。
You want to do something like this.
你想做这样的事情。
$("form#ID").submit(function(e){
e.preventDefault();
var data = {}
var Form = this;
//Gathering the Data
//and removing undefined keys(buttons)
$.each(this.elements, function(i, v){
var input = $(v);
data[input.attr("name")] = input.val();
delete data["undefined"];
});
//Form Validation goes here....
//Save Form Data........
$.ajax({
cache: false,
url : ?,
type: "POST",
dataType : "json",
data : JSON.stringify(data),
context : Form,
success : function(callback){
//Where $(this) => context == FORM
console.log(JSON.parse(callback));
$(this).html("Success!");
},
error : function(){
$(this).html("Error!");
}
});
回答by noderman
Old question, but I just ran into this situation:
老问题,但我刚刚遇到了这种情况:
jquery ajax直接执行时返回成功,但附加到按钮时返回错误,即使服务器响应为200 OK
And found out that the problem (in my case) was that calling ajax from a button
inside a form
to send JSON seems to cause JQuery to misinterpret the server response -- and always consider it an error. My solution was to change the form
to a div
or to change the button
tag to an a
tag (using Bootstrap to render a as button)
并发现问题(在我的情况下)是从 abutton
内部调用 ajaxform
以发送 JSON 似乎导致 JQuery 误解服务器响应——并且始终将其视为错误。我的解决方案是将标签更改form
为 adiv
或将button
标签更改为a
标签(使用 Bootstrap 将 a 呈现为按钮)
This worked
这有效
<div>
<button></button>
</div>
or
或者
<form>
<a></a>
</form>