javascript 解析 PHP 响应:Uncaught SyntaxError: Unexpected token <

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22571482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:23:34  来源:igfitidea点击:

Parsing PHP response: Uncaught SyntaxError: Unexpected token <

javascriptphpjqueryajax

提问by Ben Davidow

I'm using AJAX to make a call to a PHP script. The only thing I need to parse from the response is a random ID generated by the script. The problem is that the PHP script throws a number of errors. The errors are actually fine and don't get in the way of the program functionality. The only issue is that when I run

我正在使用 AJAX 调用 PHP 脚本。我唯一需要从响应中解析的是脚本生成的随机 ID。问题是 PHP 脚本引发了许多错误。错误实际上很好,不会妨碍程序功能。唯一的问题是当我跑步时

$.parseJSON(response)

I get:

我得到:

Uncaught SyntaxError: Unexpected token < 

Since the PHP response starts with an error:

由于 PHP 响应以错误开头:

<br /> 
<b>Warning</b>:

I'm wondering how to change the PHP or JS such that it can parse out the ID despite the errors.

我想知道如何更改 PHP 或 JS,以便它可以在出现错误的情况下解析出 ID。

PHP:

PHP:

  $returnData = array();
  $returnData['id'] = $pdfID;
  echo json_encode($returnData); 
  ...

JS:

JS:

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

I know that the warnings should be resolved, but the warnings are not functionality critical for now and more importantly

我知道应该解决警告,但警告现在不是功能关键,更重要的是

1) Even if these warnings are resolved new ones may come up down the line and the JSON should still be properly parsed and

1) 即使这些警告得到解决,新的警告可能会出现,JSON 仍然应该被正确解析和

2) In addition to the warnings there are 'notices' that cause the same issue.

2) 除了警告之外,还有导致相同问题的“通知”。

回答by Kris Oye

Why not deal with and eliminate the warning so that the result from the server is actually JSON?

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

回答by Ben A. Noone

There are several ways this could be solved (any one of which would work):

有几种方法可以解决这个问题(任何一种都可以):

1. Fix your warnings. :
PHP is saying something for a reason.

2.Turn off error reporting& error display:
At the top of your file place the following

1. 修正你的警告。:
PHP 是有原因的。

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

error_reporting(false);
ini_set('display_errors', false);<br/>


3.Use the output buffer:
At the top of your file place


3.使用输出缓冲区
在文件顶部

ob_start();

When you have your data array and your ready to echo to browser clear the buffer of all notices warnings etc.

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

ob_clean();
echo json_encode($returnData);
ob_flush();


4.Set a custom error handler:


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
}


5.Optionally in JavaScript:
Sanitse your response to be a JSON array:


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']; 
}

回答by Gustavo Rubio

Like everybody else has said, you SHOULD really fix your errors and handle them accordingly.

就像其他人所说的那样,你真的应该修复你的错误并相应地处理它们。

This is something more to have under circumstances that you will not control and yet want to handle errors accordingly:

在您无法控制但又希望相应地处理错误的情况下,这是更多的东西:

<?php  

//Change it to 'production' or something like that
//so that you don't send debug data on production
define('ENVIRONMENT', 'testing');

//Set your error handler globally
set_error_handler('handle_error');

function handle_error($errno, $errstr, $errfile, $errline, array $errcontext ) 
{
    //Set your headers to send a different than 200 so you can
    //catch it on error on jQuery
    header($_SERVER["SERVER_PROTOCOL"].' 500 Internal Server Error');

    //Set output as json
    header('Content-Type: application/json');

    //Create some sort of response object
    $response = new stdClass;
    $response->message = "Application error details";

    //You dont want to give debug details unless you are not on prod
    if(ENVIRONMENT == 'testing') {
        $severity = get_err_severity($errno);
        $response->error_detail = "({$severity}) [{$errfile}@L{$errline}]: {$errstr}";
        $response->context_vars = $errcontext;
    }

    //Return the json encoded error detail and exit script
    $json = json_encode($response);
    exit($json);
}

function get_err_severity($severity) 
{
    switch($severity) {
        case E_ERROR:
            return 'E_ERROR';
        case E_WARNING:
            return 'E_WARNING';
        case E_PARSE:
            return 'E_PARSE';                   
        case E_NOTICE:
            return 'E_NOTICE';
        case E_CORE_ERROR:   
            return 'E_CORE_ERROR';       
        case E_CORE_WARNING:
            return 'E_CORE_WARNING';               
        case E_COMPILE_ERROR:       
            return 'E_COMPILE_ERROR';                       
        case E_COMPILE_WARNING:     
            return 'E_COMPILE_WARNING';                               
        case E_USER_ERROR:          
            return 'E_USER_ERROR';                               
        case E_USER_WARNING:        
            return 'E_USER_WARNING';                               
        case E_USER_NOTICE:         
            return 'E_USER_NOTICE';                               
        case E_STRICT:              
            return 'E_STRICT';                               
        case E_RECOVERABLE_ERROR:   
            return 'E_RECOVERABLE_ERROR';                               
        case E_DEPRECATED:          
            return 'E_DEPRECATED';                               
        case E_USER_DEPRECATED:                 
            return 'E_USER_DEPRECATED';                               
    }
}


function test_error() 
{
    $test = array('foo'=>'bar');
    $baz = $test['baz'];
    echo $baz;
}

test_error();

回答by AJReading

I know everybody has recommended you fix the errors, I would agree, but if you do not want to then there is another a solution.

我知道每个人都建议你修复错误,我同意,但如果你不想,那么还有另一个解决方案。

If you are getting a number of warnings and expect new warnings could appear, simply disable reporting of warnings and notices:

如果您收到许多警告并预计可能会出现新警告,只需禁用警告和通知的报告:

error_reporting(E_ALL ^ (E_NOTICE | E_WARNING));

回答by Jan Sverre

If ob is enabled

如果启用了 ob

ob_end_clean();
ob_start();

echo json_encode($returnData);

Or, in top of your file

或者,在您的文件顶部

error_reporting(0);

回答by Deepak Goswami

I am sure that there would be some mistakes in your PHP code due to that error is coming please check few things:

我确信你的 PHP 代码会因为那个错误而出现一些错误,请检查几件事:

  • Make sure that there should not be more than one echoor printin your php code for printing response.
  • jQuery must be included properly.
  • And check the other php code in your function/page that should not produce any run time errors/warnings because it will also create same problem.
  • 确保在您的 php 代码中不应有多个echoprint用于打印响应。
  • 必须正确包含 jQuery。
  • 并检查您的函数/页面中不应产生任何运行时错误/警告的其他 php 代码,因为它也会产生相同的问题。

I am saying this because I have tried your code and it working fine for me you can check that also:

我这么说是因为我已经尝试过你的代码并且它对我来说工作正常你也可以检查一下:

PHP File: myContentPage.php

PHP 文件:myContentPage.php

<?php 
    $returnData = array();
    $returnData['id'] = 123;
    echo json_encode($returnData); 
?>

HTML File:

HTML文件:

<!DOCTYPE html>
<html>
    <head>
        <script type='text/javascript' src='js/jquery.js'></script>
    </head>
    <body>
        <h1>Demo Example</h1>
        <script>
            function loadResponse() {
                var dataString={};
                $.ajax({                                      
                    url:"myContentPage.php",
                    type: 'POST',
                    cache:false,
                    data: dataString,
                    beforeSend: function() {},
                    timeout:10000000,
                    error: function() { },     
                    success: function(response) {
                       var parsedResponse = $.parseJSON(response);
                        pdfID = parsedResponse['id']; 
                        console.log(pdfID);
                        alert(pdfID);
                    } 
                });
            }
            loadResponse();
        </script>
    </body>
</html>

And for handling the warnings you can do these this:

为了处理警告,您可以执行以下操作:

  • To skip warning messages, you could use something like:

    error_reporting(E_ERROR | E_PARSE);

  • or simply add the @ sign before the each line of php code on that you think warning can come
  • 要跳过警告消息,您可以使用以下内容:

    错误报告(E_ERROR | E_PARSE);

  • 或者只是在你认为可能会出现警告的每一行 php 代码之前添加 @ 符号

Happy Coding!!

快乐编码!!

回答by Mauricio Piber F?o

Script used in Ajax call just must have perfect constrution, shall not thrown any warnings just by convenience, for production you should have erros disabled, so fix it into development, edit the question with the warning that's phps givin to we help you with directly on the point.

在 Ajax 调用中使用的脚本必须具有完美的结构,不应为了方便而抛出任何警告,对于生产,您应该禁用错误,因此将其修复到开发中,使用 phps 提供的警告编辑问题,我们直接帮助您重点。

回答by Elias Soares

1st alternative:

第一种选择:

Solve the problem causing the warning. A good PHP system should never show a PHP Notice, Warning or Error. This may expose some critical information.

解决导致警告的问题。一个好的 PHP 系统不应该显示 PHP 通知、警告或错误。这可能会暴露一些关键信息。

2nd alternative:

第二种选择:

Just disable error reporting by setting

只需通过设置禁用错误报告

error_reporting(0);

error_reporting(0);

This will work, but will hide even to you any errors.

这会起作用,但会向您隐藏任何错误。

3rd alternative:

第三种选择:

Set a error handler function that treat the error and show a JSON friendly error message that does not cause any trouble.

设置一个错误处理函数来处理错误并显示不会造成任何麻烦的 JSON 友好的错误消息。

Also I recommend you to log this exceptions. It will allow you to debug any system trouble.

此外,我建议您记录此异常。它将允许您调试任何系统故障。

My recomendation?

我的推荐?

Use 1st and 3rd alternatives together, and be HAPPY!

一起使用第 1 和第 3 种选择,然后快乐!

回答by Sanjeevshrestha

You can use Try..Catch construct in the javascript function code as shown below.

您可以在 javascript 函数代码中使用 Try..Catch 构造,如下所示。

function returnReport(response) {
    try
    {
        var parsedResponse = $.parseJSON(response);
        console.log(parsedResponse);
        pdfID = parsedResponse['id'];
    }
    catch(err)
    {
       //Do something with the err
    }
}

This will work even if your php code generates debug info in response.

即使您的 php 代码在响应中生成调试信息,这也将起作用。

回答by Sebastián Olate Bustamante

If you want to see the error in JavaScript, you should handle the error on PHP with a "try catch" and the "catch" to do something like "echo json_enconde ($ error);" on this way you can parse from JavaScript.

如果您想查看 JavaScript 中的错误,您应该使用“try catch”和“catch”来处理 PHP 上的错误以执行诸如“echo json_enconde ($ error);”之类的操作。通过这种方式,您可以从 JavaScript 解析。

Example:

例子:

try{
    $returnData = array();
    $returnData['id'] = $pdfID;
    echo json_encode($returnData);
}catch (Exception $e) {
    echo json_encode($e);
}

I hope this helps :)!

我希望这有帮助 :)!