简体   繁体   中英

can not pass json array from PHP to JQuery

I have been trying to pass a simple array from PHP to JQuery. Here is what I have as far as relevant functions in my HTML/JS:

function myQuery() {

 var xmlhttp = new XMLHttpRequest();
 var url = "sandbox.php";

 xmlhttp.onreadystatechange=function() {
  if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
   myFunc(xmlhttp.responseText);
  }
 }
 xmlhttp.open("GET", url, true);
 xmlhttp.send();

}

function myFunc(response) {
 var arr = JSON.parse(response);
 document.getElementById("demco").innerHTML = arr[0];
}

For PHP I have tried:

<?php
 $arr = [4,7,2];
 echo json_encode($arr);
?>

and:

<?php
 $arr = array(4,7,2);
 echo json_encode($arr);
?>

According to my debugger it fails at JSON.parse(response) every time. What is wrong in the code here? I tried running the array, [4,7,2], through http://json.parser.online.fr/ and got no issues. I'm at my wits end, help me SE!

EDIT:

From the console: parse error in PHP on line X Where X is the line containing: $arr = [4,7,2]; Uncaught exception: SyntaxError: JSON.parse: Unable to parse value:

Error thrown at line Y, column 2 in myFunc(response) in http://... var arr = JSON.parse(response); called from line Z, column 4 in () in http://localhost/sandbox.html : myFunc(xmlhttp.responseText);

Kindly Set output page header to application/json to do it clearly. It is required to make output only in JSON code.

<?php
header('Content-Type:application/json');
$arr = array(4,7,2);
echo json_encode($arr);

This will make pure JSON output and it will be easily readable by Javascript

我在JSON传递的PHP文件顶部有一个doctype标记,并且正在加紧解析。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM