【发布时间】:2018-01-10 17:28:39
【问题描述】:
我无法弄清楚为什么我的 JSON 中的多维数组在响应中总是为空。如果我像这样声明我的 JSON 静态..
var data = {
foo: 123,
bar: 456,
cars: [
{ name:"Ford", test: 4},
{ name:"BMW" },
{ name:"Fiat"}
]
};
回复:
(index):78 Success
(index):79 {"foo":123,"bar":456,"cars":[{"name":"Ford","test":4},{"name":"BMW"},{"name":"Fiat"}]}
所以这行得通,但是当我动态添加数组时,响应是空的..
var data = {
foo: 123,
bar: 456,
};
data.cars: [];
function getMousePos(e) {
return {x:e.clientX,y:e.clientY};
}
document.onmousemove=function(e) {
var mousePos = getMousePos(e);
data.cars.push({x: mousePos.x, y: mousePos.y});
console.log(JSON.stringify(data));
};
var createCORSRequest = function(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Most browsers.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// IE8 & IE9
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
};
var url = 'http://localhost:80/t';
var method = 'POST';
var xhr = createCORSRequest(method, url);
xhr.onload = function() {
console.log("Success");
console.log(xhr.responseText);
};
xhr.onerror = function() {
console.log("Error");
};
xhr.send(JSON.stringify(data));
我发送之前的控制台..
{"foo":123,"bar":456,"cars":[{"x":320,"y":8},{"x":321,"y":20}]}
我得到的回应..
(index):79 Success
(index):80 {"foo":123,"bar":456,"cars":[]}
当我将数组推送到 JSON 字符串时,“汽车”数组在响应中总是以空结束。我已经阅读了我能找到的每个 stackoverflow 线程,但无法找出问题所在。
服务器上的响应代码
public function getJson(Request $request) {
$content = $request->json()->all();
return $content;
}
我还应该指出,我在响应服务器上使用的是 Laravel 5.4。
【问题讨论】:
-
data.cars: []应该是data.cars = []我相信 -
您在
data.cars甚至有机会被鼠标输入填充之前立即发送请求 -
@Teh 是的,你是对的。谢谢!
标签: javascript arrays json laravel