解析PHP响应:未捕获的SyntaxError:意外的令牌<

Ben*_*dow 7 javascript php ajax jquery

我正在使用AJAX来调用PHP脚本.我需要从响应中解析的唯一内容是脚本生成的随机ID.问题是PHP脚本会抛出许多错误.错误实际上很好,不会妨碍程序功能.唯一的问题是我跑的时候

$.parseJSON(response)
Run Code Online (Sandbox Code Playgroud)

我明白了:

Uncaught SyntaxError: Unexpected token < 
Run Code Online (Sandbox Code Playgroud)

由于PHP响应以错误开头:

<br /> 
<b>Warning</b>:
Run Code Online (Sandbox Code Playgroud)

我想知道如何更改PHP或JS,以便尽管有错误,它可以解析ID.

PHP:

  $returnData = array();
  $returnData['id'] = $pdfID;
  echo json_encode($returnData); 
  ...
Run Code Online (Sandbox Code Playgroud)

JS:

 function returnReport(response) {
    var parsedResponse = $.parseJSON(response);
    console.log(parsedResponse);
    pdfID = parsedResponse['id']; 
Run Code Online (Sandbox Code Playgroud)

我知道警告应该得到解决,但警告对于现在而言更重要的是功能不重要

1)即使解决了这些警告,新的可能会出现在线上,JSON仍应正确解析

2)除警告外,还有"通知"导致同样的问题.

小智 14

为什么不处理并消除警告,以便服务器的结果实际上是JSON?

  • **这个**是唯一理智的事情. (8认同)

Ben*_*one 5

有几种方法可以解决(其中任何一种都可以):

1.修正你的警告.:
PHP正在说一些原因.

2.关闭错误报告错误显示:
在文件顶部放置以下内容

error_reporting(false);
ini_set('display_errors', false);<br/>
Run Code Online (Sandbox Code Playgroud)


3.使用输出缓冲区:
位于文件顶部

ob_start();
Run Code Online (Sandbox Code Playgroud)

当您拥有数据阵列并准备回显浏览器时,请清除所有通知警告的缓冲区等.

ob_clean();
echo json_encode($returnData);
ob_flush();
Run Code Online (Sandbox Code Playgroud)


4.设置自定义错误处理程序:

set_error_handler("myCustomErrorHandler");

function myCustomErrorHandler($errno, $errstr, $errfile, $errline){
    //handle error via log-to-file etc.
    return true; //Don't execute PHP internal error handler
}
Run Code Online (Sandbox Code Playgroud)


5.可选择在JavaScript中:
将您的响应清理为JSON数组:

function returnReport(response) {
    response = response.substring(response.indexOf("{") - 1); //pull out all data before the start of the json array
    response = response.substring(0, response.lastIndexOf("}") + 1); //pull out all data after the end of the json array
    var parsedResponse = $.parseJSON(response);
    console.log(parsedResponse);
    pdfID = parsedResponse['id']; 
}
Run Code Online (Sandbox Code Playgroud)