通过AJAX向php发布JSON数组失败

时间:2021-03-09 21:29:39

I want to send JSON array via ajax call to a web service PHP. I've tried a lot of solution (most of the suggested similar answers for such question) with no clue.

我想通过ajax调用向web服务PHP发送JSON数组。我已经尝试了很多的解决方案(大多数建议类似的答案),但没有任何线索。

My JSON array structure is:

我的JSON数组结构是:

var res= [{"id":-9007199254740990,
"NW":{"x":3.97,"y":5.83},
"SE":{"x":2.72,"y":3.53},
"NE":{"x":1.97,"y":8.83},
"SW":{"x":3.87,"y":4.83}}]

and the JavaScript function that handles the request is as follows:

处理请求的JavaScript函数如下:

send_json(res); //call function
function send_json(res)
{
  var myJsonString = JSON.stringify(res);
  console.info(myJsonString);
  $.ajax({
  url:"test.php", //the page containing php script
  type: "GET", //request type
  contentType: "application/json; charset=UTF-8",
  data: {data : myJsonString} ,
  success:function(result){
    //JSON version
    console.info(result);
    }
  });
}

The php file handles the request as follows:

php文件处理请求如下:

<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET')
{
  $data = json_decode(file_get_contents("php://input"));
  print_r($data);
}
?>

I've tried also to send the JSON as key value JS:

我也尝试将JSON作为key value JS发送:

data: {data: myJsonString}

and in turn received it in php via:

然后通过php接收:

if(isset($_GET['data']))
{
echo json_decode($_GET['data']);
}

With no clue as well, the output is empty in both trials.

由于没有提示,两次试验的输出都是空的。

2 个解决方案

#1


1  

var res= [{"id":-9007199254740990,
"NW":{"x":3.97,"y":5.83},
"SE":{"x":2.72,"y":3.53},
"NE":{"x":1.97,"y":8.83},
"SW":{"x":3.87,"y":4.83}]

This is an array of json object, not a string You can pass a json object as it is

这是json对象的数组,而不是可以传递json对象的字符串

data:res,
type: "post",

Now in server do

现在在服务器

print_r($_POST);

#2


0  

Don't use GET if you are trying to send data to the server, use post instead

不要使用GET如果你想向服务器发送数据,可以使用post

type: "post",

#1


1  

var res= [{"id":-9007199254740990,
"NW":{"x":3.97,"y":5.83},
"SE":{"x":2.72,"y":3.53},
"NE":{"x":1.97,"y":8.83},
"SW":{"x":3.87,"y":4.83}]

This is an array of json object, not a string You can pass a json object as it is

这是json对象的数组,而不是可以传递json对象的字符串

data:res,
type: "post",

Now in server do

现在在服务器

print_r($_POST);

#2


0  

Don't use GET if you are trying to send data to the server, use post instead

不要使用GET如果你想向服务器发送数据,可以使用post

type: "post",