使用 jQuery 将 JSON 发送到服务器
我正在尝试将简单的数据发送到服务器,并且我需要一种“粗略且准备就绪”的方法来执行此操作。
这是我到目前为止所拥有的:
var emails = ['[email protected]', '[email protected]', '[email protected]'];
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 为空) - 我做错了什么?
I am trying to send simple data to theservre, and I need a "rough and ready" way to do this.
This is what I have so far:
var emails = ['[email protected]', '[email protected]', '[email protected]'];
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
}
});
Using Firebug, I can see that the data is POSTed to the server - however, at the server, there is no data ($_POST is empty) - what am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我们使用 json 发布所有数据。
然后在 php 中我们
这样做,这样我们甚至不会弄乱 post 变量,而且一般来说,它比让 jQuery 处理它们更快。
We post all of our data with json.
then in php we do
This way we don't even mess with the post variables, and in general, its faster than having jQuery process them.
您的数据字段应该包含一个带有键值对的对象,因为它被编码为 POST 键值对。
然后在 PHP 端您可以通过以下方式访问数据:
Your data field should contain an object with key-value pairs, because it gets encoded as POST key-values pairs.
Then on the PHP side you can access the data as:
PHP 通过解析接收到的数据来填充
$_POST
。但是,它只识别表单编码的数据,无法自动解析 JSON 数据。所以在这种情况下$_POST
将毫无用处。您需要获取原始帖子数据并使用json_decode
解析它。PHP populates
$_POST
by parsing the data received. However, it only knows form-encoded data, JSON data cannot be parsed automatically. So$_POST
will be useless in this case. You need to get the raw post data and parse it withjson_decode
.