这是我正在使用的以下代码。
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 数据?
最佳答案
您的代码有几处“错误”。
首先是 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 脚本。具有数字索引的数组没有“数据”键。尝试:
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 请求是异步。控制台中显示的 undefined
是 JS 的东西,console.log
的结果,它返回 undefined。
AJAX 请求尚未执行。要查看您的请求实际执行的操作,请打开控制台中的网络 选项卡(左起第三个)。在底部,您会在某处看到 XHR。单击它,您应该会看到一个 POST 请求发出。您可以单击它,然后查看 header 、响应以及其他...
关于javascript - 无法通过ajax将json数据传递给php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20610822/