how to use JSON.stringify and json_decode() properly

后端 未结 7 1692
野性不改
野性不改 2020-12-08 06:08

Im trying to pass a mulitidimensional Javascript array to another page on my site by:

  • using JSON.stringify on the array

  • assigning the result

7条回答
  •  北荒
    北荒 (楼主)
    2020-12-08 06:53

    None of the other answers worked in my case, most likely because the JSON array contained special characters. What fixed it for me:

    Javascript (added encodeURIComponent)

    var JSONstr = encodeURIComponent(JSON.stringify(fullInfoArray));
    document.getElementById('JSONfullInfoArray').value = JSONstr;
    

    PHP (unchanged from the question)

    $data = json_decode($_POST["JSONfullInfoArray"]);
    var_dump($data);
    
    echo($_POST["JSONfullInfoArray"]);
    

    Both echo and var_dump have been verified to work fine on a sample of more than 2000 user-entered datasets that included a URL field and a long text field, and that were returning NULL on var_dump for a subset that included URLs with the characters ?&#.

提交回复
热议问题