无法通过ajax将json数据传递给php

时间:2013-12-16 12:19:24

标签: javascript php jquery ajax json

这是我正在使用的以下代码。

的Javascript

    <script type="text/javascript">
    var stuff = new Object();
    stuff[0] = {'id':'0','value':'no','type':'img','filename':'hehehehe.jpg','filesize':'0.3356 MB','fileformat':'jpg','change':'0','caption':'this is a description about the stuff inserted'};
    stuff[1] = {'id':'1','value':'yes','type':'img','filename':'hehehehe.jpg','filesize':'0.3356 MB','fileformat':'jpg','change':'0','caption':'this is a description about the stuff inserted'};
    stuff[2] = {'id':'2','value':'yes','type':'img','filename':'hsdssssdfhe.jpg','filesize':'0.4356 MB','fileformat':'png','change':'0','caption':'description 2 of the image'};
    stuff[3] = {'id':'3','value':'yes','type':'vid','filename':'hehehehe.mp4','filesize':'56 MB','fileformat':'mp4','change':'0','caption':'this is video'};
    console.log(stuff);

    $.ajax({
    type: "POST",
    dataType: "json",
    url: "test1.php",
    data: stuff,
    success: function(data){
        alert('Items added');
    },
    error: function(e){
        console.log(e.message);
    }
    });
    </script>

test1.php

    <?php
    $arr = json_decode($_POST['data'], true);
    print_r($arr);
    ?>

Chrome上的控制台显示对象,但php显示未定义..如何在PHP中使用json数据? enter image description here

3 个答案:

答案 0 :(得分:3)

使用您的代码,&#34;错误&#34; 有几件事 首先是JS:

stuff = new Object();

现在这不是错误的,但是通常建议来调用这样的对象构造函数。你应该养成使用文字符号的习惯。看作调用构造函数可能会导致意外结果:

var arr = new Array(10);
var arr2 = [10];
console.log(arr2.length);//logs 1, the array looks like this [10]
console.log(arr.length);//logs 10, arr is [undefined, undefined, undefined,...]
//but at the same time:
var arr3 = new Array(1,2);//is identical to:
var arr4 = [1,2];//both create an array containing 2 numbers: [1,2]

同样适用于Object

var o = new Object();//same as var o = {};
var o2 = new Object('foobar');
console.log(o2);//String {0: 'f', 1: 'o', 2: 'o', ...}
//and so on:
new Object(true);// === new Boolean(true)
new Object(123);// === new Number(123);

但您已将此Object用作Array !!这没有意义,只需写下:

stuff = [];
//or
stuff = [ {id: 0, ...}];//initialize array from the off

当您将对象用作数组时,JS不会抱怨,因为数组Object实例:

console.log(Object.getPrototypeOf(Array.prototype));//Object!

Array是一个增强的Object,基本上是

接下来,PHP方面:

$_POST['data'];

如上所示,您只需向PHP脚本发送数组即可。具有数字索引的数组没有&#34;数据&#34;键的。尝试:

var_dump($_POST);

您将看到您实际发送到服务器的内容 总而言之,你真正想要做的事情,我认为是这样的:

$.ajax({ url: 'your.php',
    data: {data: stuff},//send an object, with property data
    success: function(data)
    {
        console.log(data);//log the PHP response
    }
});

您似乎也忘记了AJAX请求是 asynchonous 。在控制台中显示的undefined是JS的东西,是console.log的结果,它返回undefined。
AJAX请求尚未执行。要查看您的请求实际执行的操作,请在控制台中打开网络标签(左起第三个)。在底部,您会在某处看到 XHR 。单击它,您应该看到一个POST请求。你可以点击它,看看标题,响应和什么不是......

答案 1 :(得分:1)

您正在阅读名为data的帖子参数但不发送

尝试

data: {
    data: JSON.stringify(stuff)
}

由于您正在传输json数据,请将数据作为请求体发送,如

$.ajax({
    type: "POST",
    dataType: "json",
    url: "test1.php",
    contentType: 'application/json',
    data: JSON.stringify(stuff),
    success: function (data) {
        alert('Items added');
    },
    error: function (e) {
        console.log(e.message);
    }
});

然后在服务器端(不是PHP人员,所以不确定)使用http-get-request-body

$arr = json_decode(http_get_request_body(), true);

答案 2 :(得分:0)

我能够让它工作..向所有人寻求建议..只是微小的改变..

JS

    <script type="text/javascript">
    var stuff = [];   // changed from var stuff = new object();
    stuff[0] = {'id':'0','value':'no','type':'img','filename':'hehehehe.jpg','filesize':'0.3356 MB','fileformat':'jpg','change':'0','caption':'this is a description about the stuff inserted'};
    stuff[1] = {'id':'1','value':'yes','type':'img','filename':'hehehehe.jpg','filesize':'0.3356 MB','fileformat':'jpg','change':'0','caption':'this is a description about the stuff inserted'};
     stuff[2] = {'id':'2','value':'yes','type':'img','filename':'hsdssssdfhe.jpg','filesize':'0.4356 MB','fileformat':'png','change':'0','caption':'description 2 of the image'};
     stuff[3] = {'id':'3','value':'yes','type':'vid','filename':'hehehehe.mp4','filesize':'56 MB','fileformat':'mp4','change':'0','caption':'this is video'};
     console.log(stuff);
    var a = JSON.stringify(stuff);  //this is required otherwise it sends the object to php rather JSON string.
    $.ajax({
    type: "POST",
    dataType: "json",
    url: "test1.php",
    data: a,
    success: function(data){

    },
    error: function(e){
        console.log(e.responseText);   //changed from e.message no message argument in error response . thanks to @user555 valuable suggestion
    }
    });
    </script>

test1.php

    <?php  $data = $_POST['data'];
    $arr = json_decode($data, true);
    echo $arr[3]['type'];
    ?>    

控制台中的输出为vid。它正确返回数组值。它将在控制台中显示结果。这是一个工作示例,任何人都可以复制和粘贴以进行更多探索。它对我帮助很大,它肯定对你有帮助..