我有一个期望接收 json 的 webservice,就像这样:
{"first_name":"test","last_name":"teste","email":"[email protected]","mobile":"+44 22 2222 2222", "password":"testing"}
我的 jquery ajax 调用:
$.ajax({
type: "POST",
url: hb_base_url + "consumer",
contentType: "application/json",
dataType: "json",
data: {
first_name: $("#namec").val(),
last_name: $("#surnamec").val(),
email: $("#emailc").val(),
mobile: $("#numberc").val(),
password: $("#passwordc").val()
},
success: function(response) {
console.log(response);
},
error: function(response) {
console.log(response);
}
});
有没有办法检查我发送数据的格式?我应该是没有向服务器发送正确的 JSON 格式(这是验证的第一步)。
是我的 jquery 代码发送了有效的 JSON 还是我遗漏了什么?
您实际上并没有发送 JSON。您传递的是一个对象作为 "数据",但您需要对对象进行字符串化,然后传递字符串。
你的dataType:"json"
只是告诉jQuery你想让它解析返回的JSON,并不意味着jQuery会自动对你的请求数据进行字符串化。
改为
$.ajax({
type: "POST",
url: hb_base_url + "consumer",
contentType: "application/json",
dataType: "json",
data: JSON.stringify({
first_name: $("#namec").val(),
last_name: $("#surnamec").val(),
email: $("#emailc").val(),
mobile: $("#numberc").val(),
password: $("#passwordc").val()
}),
success: function(response) {
console.log(response);
},
error: function(response) {
console.log(response);
}
});
我从来没有用过这种方法。 我总是这样做(希望能有所帮助):
var obj = {};
obj.first_name = $("#namec").val();
obj.last_name = $("#surnamec").val();
obj.email = $("#emailc").val();
obj.mobile = $("#numberc").val();
obj.password = $("#passwordc").val();
然后在您的 ajax 中
$.ajax({
type: "POST",
url: hb_base_url + "consumer",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(obj),
success: function(response) {
console.log(response);
},
error: function(response) {
console.log(response);
}
});