简体   繁体   English

使用Javascript从PHP获取JSON数据:

[英]Get JSON data from PHP using Javascript:

In my javascript I'm getting this error: 在我的JavaScript中,我收到此错误:

Uncaught SyntaxError: Unexpected token P in JSON at position 0, at JSON.parse (), at XMLHttpRequest.req.onreadystatechange 未捕获到的SyntaxError:JSON中位置0处的意外令牌P,在JSON.parse()处,在XMLHttpRequest.req.onreadystatechange

when trying to receive some stuff from a PHP script. 尝试从PHP脚本接收某些内容时。 I've seen some similar questions but I couldn't find a solution for my case. 我已经看到了一些类似的问题,但是找不到针对我的案例的解决方案。

My server PHP code: 我的服务器PHP代码:

<?php
header('Content-Type: application/json');
$myObj->name = "John";
$myObj->age = 30;
$myObj->city = "New York";
$myJSON = json_encode($myObj,JSON_UNESCAPED_UNICODE);
echo $myJSON;
?>

My client javascript: 我的客户javascript:

var req = new XMLHttpRequest();
req.onreadystatechange = function () {
    if (this.readyState == XMLHttpRequest.DONE && this.status == 200) {
        var s = req.responseText;
        var users = JSON.parse(s);
        console.table(s);
    } 
}
req.open("GET", "./get_info.php", true);

When I run the PHP file using the browser I get this: 当我使用浏览器运行PHP文件时,得到以下信息:

{"name":"John","age":30,"city":"New York"}

which I believe is correct. 我认为是正确的。

Any suggestion? 有什么建议吗?

Your code is working fine , you could check if you are getting any warning in php response which cause an error in JSON.parse at client side, meanwhile same error I got while running your script in my system. 您的代码运行正常 ,您可以检查是否在php响应中收到任何警告,从而在客户端导致JSON.parse错误,与此同时,我在系统中运行脚本时遇到了相同的错误。 Getting Response from php - 从php获取响应-

<br />
<b>Warning</b>:  Creating default object from empty value in <b>/opt/lampp/htdocs/tst/get_info.php</b> on line <b>5</b><br />
{"name":"John","age":30,"city":"New York"}

At Client Side : 在客户端:

Uncaught SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at XMLHttpRequest.req.onreadystatechange 

Fixed this issue by disabling the warning in my php code - 通过禁用我的PHP代码中的警告来解决此问题-

error_reporting(E_ERROR | E_PARSE);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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