Jquery 以json格式发布
对不起,英语不好:) 我试图为用php/python编写的restapi发布json格式的表单。如果我使用json,我无法访问发布的数据。请参见下面的场景 非json post的代码Jquery 以json格式发布,jquery,ajax,json,post,Jquery,Ajax,Json,Post,对不起,英语不好:) 我试图为用php/python编写的restapi发布json格式的表单。如果我使用json,我无法访问发布的数据。请参见下面的场景 非json post的代码 jQuery(document).ready(function($) { $.post( "http://localhost:8000/api/v1/entry/?format=json", { "body": "This will prbbly b
jQuery(document).ready(function($) {
$.post(
"http://localhost:8000/api/v1/entry/?format=json",
{
"body": "This will prbbly be my lst edited post.",
"pub_date": "2011-05-22T00:46:38",
"slug": "another-post",
"title": "Another Post",
"username":"admin",
"password":"admin"
},
function(responseText){
$("#result").html(responseText);
},
"html"
);
})
服务器响应
Array
(
[body] => This will prbbly be my lst edited post.
[pub_date] => 2011-05-22T00:46:38
[slug] => another-post
[title] => Another Post
[username] => admin
[password] => admin
)
Array
(
)
Json Post的代码
jQuery(document).ready(function($) {
var data = JSON.stringify({
"body": "This will prbbly be my lst edited post.",
"pub_date": "2011-05-22T00:46:38",
"slug": "another-post",
"title": "Another Post",
"username":"admin",
"password":"admin"
});
$.post(
"testpost.php",
data,
function(responseText){
$("#result").html(responseText);
},
"html"
);
})
服务器响应
Array
(
[body] => This will prbbly be my lst edited post.
[pub_date] => 2011-05-22T00:46:38
[slug] => another-post
[title] => Another Post
[username] => admin
[password] => admin
)
Array
(
)
嗯,您还没有将该值赋给任何参数,因此PHP将无法填充
$\u POST
数组
将其分配给参数,例如,json
:
$.post("testpost.php", {json: data}, ...);
然后,您将能够通过以下方式访问它:
$_POST['json'];
或者,如果您使用PECL,您可以调用来获取数据。好吧,您还没有将值分配给任何参数,因此PHP将无法填充
$\u POST
数组
将其分配给参数,例如,json
:
$.post("testpost.php", {json: data}, ...);
然后,您将能够通过以下方式访问它:
$_POST['json'];
或者,如果您使用PECL,您可以调用来获取数据。这是正常的响应,数据必须是键值对的数组/对象或正确编码的查询字符串,类似于key=value&key2=value2。。。 如果您想像在服务器端那样获取发布的数据,您应该自己阅读输入,类似这样的内容:
$jsonDatas = file_get_contents('php://input')
在js中更简单的方法:
data = { json: JSON.stringify({...}) }
然后在$\u POST['json']服务器端获取结果
如果您想查看我的一个类,以帮助您使用php服务器端的json服务:这是正常响应,数据必须是键值对的数组/对象或正确编码的查询字符串,类似于key=value&key2=value2。。。 如果您想像在服务器端那样获取发布的数据,您应该自己阅读输入,类似这样的内容:
$jsonDatas = file_get_contents('php://input')
在js中更简单的方法:
data = { json: JSON.stringify({...}) }
然后在$\u POST['json']服务器端获取结果
如果您需要,可以在这里检查我的一个类,以帮助您使用php服务器端的json服务:eval(data)可以吗?或者它将简单地将json转换回object??只是好奇:)用PHP还是JavaScript?在PHP中使用
json\u decode
,在JavaScript中使用json.parse
。eval(数据)可以吗?或者它将简单地将json转换回object??只是好奇:)用PHP还是JavaScript?在PHP中使用json\u decode
,在JavaScript中使用json.parse
。