使用jQuery将JSON发送到服务器

oom*_*pah 5 php jquery

我试图将简单的数据发送到服务器,我需要一个"粗略和准备"的方式来做到这一点.

这是我到目前为止:

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
    }
});
Run Code Online (Sandbox Code Playgroud)

使用Firebug,我可以看到数据被POST到服务器 - 但是,在服务器上,没有数据($ _POST为空) - 我做错了什么?

Rah*_*hly 7

我们用json发布所有数据.

var myobj = { this: 'that' };
$.ajax({
  url: "my.php",
  data: JSON.stringify(myobj),
  processData: false,
  dataType: "json",
  success:function(a) { },
  error:function() {}
});
Run Code Online (Sandbox Code Playgroud)

然后在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"
  ));
?>
Run Code Online (Sandbox Code Playgroud)

这样我们甚至不会搞乱post变量,一般来说,它比jQuery处理它们更快.