开发者

Sending JSON to server, using jQuery

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 = ['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
    }
});

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?


We post all of our data with json.

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

then in php we do

<?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"
  ));
?>

This way we don't even mess with the post variables, and in general, its faster than having jQuery process them.


Your data field should contain an object with key-value pairs, because it gets encoded as POST key-values pairs.

data = {my_json: encoded_string};

Then on the PHP side you can access the data as:

$data = json_decode($_POST['my_json']);


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 with json_decode.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜