我正在尝试将简单的数据发送到服务器,我需要一个粗略的,准备好的"这样做的方法。
这是我到目前为止所做的:
var emails = ['a@123.com', 'b@123.com', 'c@123.com'];
var ruff_json = "{ 'emails': [";
for (i in emails)
ruff_json += ((i == 0) ? '' : ', ') + '\''+emails[i]+'\'';
ruff_json += '] }';
jQuery.ajax({
type: 'POST',
url: '1.php',
data: ruff_json,
dataType: "json",
timeout: 2000,
success: function(result){
//do something
},
error: function (xhr, ajaxOptions, thrownError){
//do something
}
});
使用Firebug,我可以看到数据被POST到服务器 - 但是,在服务器上,没有数据($ _POST为空) - 我做错了什么?
答案 0 :(得分:7)
我们用json发布所有数据。
var myobj = { this: 'that' };
$.ajax({
url: "my.php",
data: JSON.stringify(myobj),
processData: false,
dataType: "json",
success:function(a) { },
error:function() {}
});
然后在php中我们做
<?php
$json = json_decode(file_get_contents("php://input"), true);
// Access your $json['this']
// then when you are done
header("Content-type: application/json");
print json_encode(array(
"passed" => "back"
));
?>
这样我们甚至不会搞乱post变量,一般来说,它比jQuery处理它们更快。
答案 1 :(得分:2)
您的数据字段应包含具有键值对的对象,因为它被编码为POST键值对。
data = {my_json: encoded_string};
然后在PHP端,您可以访问数据:
$data = json_decode($_POST['my_json']);
答案 2 :(得分:0)
PHP通过解析收到的数据来填充$_POST
。但是,它只知道表单编码数据,无法自动解析JSON数据。所以$_POST
在这种情况下将毫无用处。您需要get the raw post data并使用json_decode
解析它。