如何使用JQuery发布JSON数据?
我想将Json发布到同一服务器上的web服务。但我不知道如何使用JQuery发布Json。我已尝试使用此代码:如何使用JQuery发布JSON数据?,jquery,json,ajax,http-post,Jquery,Json,Ajax,Http Post,我想将Json发布到同一服务器上的web服务。但我不知道如何使用JQuery发布Json。我已尝试使用此代码: $.ajax({ type: 'POST', url: '/form/', data: {"name":"jonas"}, success: function(data) { alert('data: ' + data); }, contentType: "application/json", dataType: 'json' });
$.ajax({
type: 'POST',
url: '/form/',
data: {"name":"jonas"},
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
但使用此JQuery代码,服务器上的数据不会作为Json接收。这是服务器上的预期数据:{“name”:“jonas”}
但是使用JQuery服务器接收name=jonas
。或者换句话说,它是“urlencoded”数据,而不是Json
是否有任何方法可以使用JQuery以Json格式发布数据而不是URL编码的数据?或者我必须使用手动ajax请求吗?您传递的是一个对象,而不是JSON字符串。传递对象时,jQuery使用将对象序列化为名称-值对
如果将数据作为字符串传递,则不会序列化:
$.ajax({
type: 'POST',
url: '/form/',
data: '{"name":"jonas"}', // or JSON.stringify ({name: 'jonas'}),
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
根据lonesomeday的回答,我创建了一个
jpost
,它封装了某些参数
$.extend({
jpost: function(url, body) {
return $.ajax({
type: 'POST',
url: url,
data: JSON.stringify(body),
contentType: "application/json",
dataType: 'json'
});
}
});
用法:
$.jpost('/form/', { name: 'Jonh' }).then(res => {
console.log(res);
});
使用
Promise
并检查body
对象是否是有效的JSON。如果没有,将返回承诺拒绝
var DoPost = function(url, body) {
try {
body = JSON.stringify(body);
} catch (error) {
return reject(error);
}
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: url,
data: body,
contentType: "application/json",
dataType: 'json'
})
.done(function(data) {
return resolve(data);
})
.fail(function(error) {
console.error(error);
return reject(error);
})
.always(function() {
// called after done or fail
});
});
}
上面的答案很好,但我建议在发布之前将JSON数据保存到变量中,这样在发送长表单或处理大数据时会更简洁一些
var数据={
“姓名”:“jonsa”,
“电子邮件”:qwerty@gmail.com",
“电话”:1223456789
};
$.ajax({
键入:“POST”,
url:“/form/”,
数据:数据,
成功:函数(数据){alert('data:'+data);},
contentType:“应用程序/json”,
数据类型:“json”
});代码>我尝试了Ninh Pham的解决方案,但直到我调整了它,它才对我起作用-见下文。删除contentType,不要对json数据进行编码
$.fn.postJSON = function(url, data) {
return $.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json'
});
您可以使用ajax发布数据,如下所示:
$.ajax({
url: "url",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ name: 'value1', email: 'value2' }),
success: function (result) {
// when call is sucessfull
},
error: function (err) {
// check the err for error details
}
}); // ajax call closing
请使用$.post而不是$.ajax。@user3746259为什么要使用$.post
?它(a)只是$.ajax
的包装器,(b)无法执行此处所需的操作(即contentType
属性)。直到,您知道,jQuery 3,也就是说,它仍然在未来,不必管这个答案是在四年前写的。@lonesomeday谢谢。我也遇到了同样的问题,在将对象转换为字符串后,它成功了。@lonesomeday我不得不使用您的方法,甚至在3.2中,强制contentType转换为json。Shuggyou忘记了对数据进行字符串化。这不会发布JSON请求正文