【问题标题】:Empty response when pushing arrays to JSON将数组推送到 JSON 时的空响应
【发布时间】: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


【解决方案1】:

我可以看到 2 个错误:

  1. 定义 Cars 对象,如 data.cars = [];而是使用 data.cars: [];

  2. Ajax 调用本质上是异步的,根据您编写的代码,xhr.send 将在 document.onmousemove 函数之前调用。 onmousemove 需要触发 mousemove 事件,但 xhr.send 不在任何函数内,因此在页面加载后立即被调用。

因此,您必须进行 2 处更改:

  1. 定义 Cars 对象,如 data.cars = [];
  2. mousemove 函数(即在 mousemove 或其他函数内部)分配数据后调用 xhr.send 方法

【讨论】:

    猜你喜欢
    • 2022-11-19
    • 1970-01-01
    • 2019-08-18
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    • 2015-09-13
    • 2020-04-22
    • 1970-01-01
    相关资源
    最近更新 更多