簡體   English   中英

將數組推送到 JSON 時響應為空

[英]Empty response when pushing arrays to JSON

我不明白為什么我在 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 字符串時,響應中的“cars”數組始終為空。 我已經閱讀了我能找到的所有關於此的 stackoverflow 線程,但無法找出問題所在。

服務器上的響應代碼

public function getJson(Request $request) {

    $content = $request->json()->all();


    return $content;
}

我還應該指出,我在響應服務器上使用 Laravel 5.4。

我可以看到 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方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM