js到的json无法打开流:http请求失败


json from js to failed to open stream: http request failed

我正试图将一些json数据从js发送到php,并通过REST.将其传递给mongo

以下输出json字符串(如果我只是把它作为字符串放在PHP文件中,稍后会很好地工作,请参阅下面的片段)。

JS发送json:

var s = JSON.stringify(send); //s contains previous data in arrays, etc
ic(s);
function ic(s){
    var ajaxUrl = './iM.php';
    $.getJSON(ajaxUrl, 
    {da: s}, 
    function(data) {
       console.log (data);
});
}

在iM.php:中

$s = $_GET["da"]; // <-- doesn't work
//$s = '{"r":"pax","c":1,"w":["kiwi","melon"],"g":["cat","dog"]}'; //<-- works fine
$opts = array(
    "http" => array(
        "method"  => "POST",
        "header"  => "Content-type: application/json",
        "content" => $s,
    ),
);
$context = stream_context_create($opts);
$result = file_get_contents("https://api.mongolab.com/api/1/databases/$db/collections/$collection?apiKey=$key", false, $context);
var_dump($result); // Dumps the response document

在firefox调试器中,我可以看到文件实际上正在被调用,但没有添加任何数据。

创建error_log文件:无法打开流:HTTP请求失败!HTTP/1.1 400错误请求

我还在php中尝试了urlencode($s),但仍然不起作用。$db、$collection和$key是在php中定义的,没有问题。

我错过了什么?

基本上JSON.stringfy(send)函数的设计方式是,它将使您的JSON变成您所得到的。

JSON.stringify(value[, replacer[, space]])

您应该正确使用此功能。阅读文档了解更多信息。如果您将输入值作为JS数组或JS对象,它基本上是有用的可以将其转换为单个字符串。

只有当您试图字符串化一个已经是字符串格式的json时,才会得到"{/"r/":/"pax/",/"c/":1"。

这些:

var s = ['1','2','3'];
and 
var s = "['1','2','3']";

是完全不同的东西。

如果您正在发送一个数组或json对象,您甚至可以直接发送它使用上面的代码。例如:

send = {"r":"pax","c":1,"w":["kiwi","melon"],"g":["cat","dog"]};
ic(send);
function ic(s){
    var ajaxUrl = 'im.php';
    $.getJSON(ajaxUrl, 
    {da: s}, 
    function(data) {
       console.log (data);
});
}

确保在php端正确处理数组。就像如果你想返回json,do:

$s = $_GET["da"]; //this will be array.
var jsonObject = json_encode($s);

或者你可以在那里把它串起来,然后提供。

或者只发送字符串,然后使用json_decode使其在php 中为json