未捕获的SyntaxError:意外的令牌&lt;在JSON位于JSON.parse的位置0(<anonymous>)

时间:2017-03-26 01:03:06

标签: javascript php jquery arrays json

我想将一个数组从PHP文件传递给JavaScript并存储在JavaScript数组中。这是JavaScript代码:

xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange=function(){
             if (xmlhttp.readyState==4 && xmlhttp.status==200)
             {
                    nameData = JSON.parse(xmlhttp.responseText); 
                    console.log(xmlhttp.responseText);
                }
            }
            xmlhttp.readyState=4;
            xmlhttp.open("GET","mapPHPname.php?Zip="+zipcode,true);
            xmlhttp.send();

PHP文件:

<?php
$zip=isset($_GET['Zip']);
include 'dbconnect.php';
$sql="Select `name` from doctor where `zip` LIKE $zip";
$result = mysql_query( $sql, $conn );
$num_rows = mysql_num_rows($result);
array(name);
if($num_rows>=1)
{
    $count=0;
    while($res_array = mysql_fetch_assoc($result))
    {
        $name[$count]=$res_array['name'];
    }
}
else
{
    $name[0]="kashyap"; 
}
echo json_encode($name);
?>

我收到此错误:

  

未捕获的SyntaxError:意外的令牌&lt;在位置0的JSON中       在JSON.parse(&lt; anonymous&gt;)

1 个答案:

答案 0 :(得分:0)

1-您不以这种方式声明数组:array(name)

请改为:$name = array()$name = []

2-并引用您的包含include 'dbconnect.php';

3-在count$name[count]=$res_array['name'];处正确访问变量count应为$count

而你实际上并没有循环它。保存到$count++数组后,您应该$name