jQuery POST 请求 - 返回 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15130868/
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
jQuery POST Request - returning JSON
提问by Nik
I want to use the jQuery $.ajax
to make a POST call sending some information (via POST like: page.aspx?var1=value
....).
我想使用 jQuery$.ajax
进行 POST 调用以发送一些信息(通过 POST 像:page.aspx?var1=value
....)。
But I also want jQuery to handle that the service is returning JSON so that I get back a JSON object.
但我也希望 jQuery 处理该服务正在返回 JSON,以便我返回一个 JSON 对象。
var data = {name: _name, ...};
var request = $.ajax({
url: url,
type: "post",
data: data,
//dataType: "json"
});
As soon as I use dataType: "json"
, which allows me to receive the JSON object I get an parseerror on the request!
一旦我使用dataType: "json"
,它允许我接收 JSON 对象,我就会收到请求的解析错误!
Hope you can help me out with that!
希望你能帮我解决这个问题!
THANKS IN ADVACE!
提前致谢!
回答by Vimal Patel
From the requested url you have to make data in JSON format like
从请求的 url 中,您必须以 JSON 格式制作数据,例如
echo json_encode($response);
and then you will get that response JSON in success function like this:
然后您将在成功函数中获得该响应 JSON,如下所示:
$.ajax({
type:"POST",
url: "your_url",
data:data,
success: function (response){
var arr = $.parseJSON(response);
}
});
回答by Dipesh Parmar
make sure your serverside script return encoded json.
确保您的服务器端脚本返回编码的 json。
In php use json_encode()
.
在 php 中使用json_encode()
.
echo json_encode($response);
also set dataType : 'json'
in $.ajax
call.
也设置dataType : 'json'
在$.ajax
通话中。
回答by Deb
Firstly post request does not have the parameters appended after the URL. The format you have specified is for GET request. You can achieve the same goal with following:
首先发布请求没有在 URL 后附加参数。您指定的格式用于 GET 请求。您可以通过以下方式实现相同的目标:
$.post(
'/yourURLL',
{'data' : dataJson},
function(data){
handleIncomingJSON(data);
}).error(function(data, textStatus){handleUnsuccessfulSave(data, textStatus)});
回答by icc97
As per the jQuery $.post
documentation, I highly recommend implementing all the major callback methods (done
, fail
, always
) initially so that if there were errors with your JSON response then they don't get hidden:
根据jQuery$.post
文档,我强烈建议最初实现所有主要的回调方法 ( done
, fail
, always
),这样如果您的 JSON 响应出现错误,它们就不会被隐藏:
var jqxhr = $.post(
"example.php",
function(response) {var arr = JSON.parse(response);},
'json'
)
.done(function() {console.log( "second success" );})
.fail(function() {console.log( "error" );})
.always(function() {console.log( "finished" );});