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

时间:2014-03-21 23:45:20

标签: javascript php jquery ajax

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

$.parseJSON(response)

我明白了:

Uncaught SyntaxError: Unexpected token < 

由于PHP响应以错误开头:

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

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

PHP:

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

JS:

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

我知道警告应该得到解决,但警告对于现在来说并不重要,更重要的是

1)即使解决了这些警告,也可能会出现新的警告,并且JSON仍然应该正确解析并且

2)除了警告之外,还有通知&#39;导致同样的问题。

11 个答案:

答案 0 :(得分:14)

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

答案 1 :(得分:5)

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

<强> 1。修正你的警告。 :
由于某种原因,PHP正在说些什么
2。关闭error reporting&amp; error display
在文件顶部放置以下内容

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


3。使用output buffer
位于文件顶部

ob_start();

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

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


4. 设置custom error handler

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。可选择在JavaScript中:
Sanitse你的回应是一个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']; 
}

答案 2 :(得分:1)

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

在您无法控制但又想要相应处理错误的情况下,这是更多的事情:

<?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();

答案 3 :(得分:0)

虽然这并没有解决更广泛的警告问题,但我使用这个黑客来解析响应:

function returnReport(response) {
    var pdfID = parseID(response);
    ...
}

function parseID(response) {
    var responseIndex = response.indexOf('{"id');
    var start = responseIndex + 7;
    var pdfID = response.slice(start, start + 6);
    return pdfID;
}

答案 4 :(得分:0)

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

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

error_reporting(E_ALL ^ (E_NOTICE | E_WARNING));

答案 5 :(得分:0)

如果启用了ob

ob_end_clean();
ob_start();

echo json_encode($returnData);

或者,在您的文件顶部

error_reporting(0);

答案 6 :(得分:0)

我确信您的PHP代码会出现一些错误,因为错误即将来临请查看以下内容:

  • 确保您的php代码中不应有多个echoprint用于打印回复。
  • 必须正确包含jQuery。
  • 并检查您的函数/页面中的其他php代码,它们不会产生任何运行时错误/警告,因为它也会产生同样的问题。

我之所以这样说是因为我已经尝试过您的代码并且它对我很好,您也可以检查:

PHP文件:myContentPage.php

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

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>

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

  • 要跳过警告消息,您可以使用以下内容:

    error_reporting(E_ERROR | E_PARSE);

  • 或者只是在每行php代码之前添加@符号,您认为警告可以来

快乐编码!!

答案 7 :(得分:0)

Ajax调用中使用的脚本必须具有完美的构造,不能仅仅为了方便而抛出任何警告,对于生产你应该禁用错误,所以将其修复为开发,编辑问题并发出警告,我们会帮助你直接点上。

答案 8 :(得分:0)

第一种选择:

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

第二种选择:

只需设置

即可停用错误报告

error_reporting(0);

这会有效,但会隐藏任何错误。

第三种选择:

设置错误处理函数,该函数处理错误并显示不会导致任何问题的JSON友好错误消息。

另外,我建议您记录此例外情况。它将允许您调试任何系统故障。

我的推荐?

一起使用第一和第三种选择,并且快乐!

答案 9 :(得分:0)

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

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

即使你的php代码生成调试信息作为响应,这也会有效。

答案 10 :(得分:0)

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

示例:

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

我希望这会有所帮助:)!

相关问题