Passing PHP parser errors back in JSON?

问题: I have an HTML page that sends a JQuery Ajax call to a PHP page and is expecting a JSON response. If the PHP has a parser error, the error is returned to the call, but not...

问题:

I have an HTML page that sends a JQuery Ajax call to a PHP page and is expecting a JSON response. If the PHP has a parser error, the error is returned to the call, but not in JSON format, so it ends up throwing a "JSON.parse: unexpected character" error on the Ajax side.

Is there a way to get the PHP to send the error message back in a JSON-friendly format? (Yes, it sends the error to event.log in the PHP file's directory, but I'd rather not have to jump through the hoops of accessing it each time there's a problem with the script.)

Edit: Somebody asked for the code - what I mean is, something like this:

First, the "bad" PHP script, oops.php:

<?php
    $x = "There's no terminating semicolon"
    echo json_encode($x);
?>

Now, the HTML page that calls it, oops.html:

<html>
<head><title>OOPS</title></head>
<body>
<div id="text_goes_here"></div>
</body>

<script>
var $outputText = "Text goes here";

$.ajax({
    url:"oops.php",
    type:"GET",
    data: {},
    success:function(data) {
        outputText = "Success:<br />";
        for (var d in data) {
            outputText += (data[d] + "<br />");
        }
        document.getElementById("text_goes_here").innerHTML = outputText;
    }, 
    error:function(xhr, status, message) {
        outputText = "Error:<br />";
                   + "Status: " + status + "<br />"
                   + "Message: " + message + <br />";
        document.getElementById("text_goes_here").innerHTML = outputText;
    },
    dataType:"json"
});
</script>
</html>

The problem appears to be, the PHP returns an error message, but not in a JSON format, so the .ajax call's JSON parser doesn't understand what it is and throws an error of its own. I want to be able to pass the script error that the PHP script generated back to the call in a format that the call can read.


回答1:

Use try-catch block.

This article shows how to write a AJAX handler with exceptions handled.

Here's the PHP code.

<?php
include_once $_SERVER['DOCUMENT_ROOT'] . '/inc/ajax.inc.php'; 
try { 
    if ($_SERVER['REQUEST_METHOD'] !== "POST") {
        throw new Exception('Invalid Request', 2000);
    } else {
        // status is true if everything is fine
        exit(json_encode(
            array(
                'status' => true
            )
        ));
    }
} catch(Exception $e) {

    echo json_encode(
        array(
            'status' => false,
            'error' => $e -> getMessage(),
            'error_code' => $e -> getCode()
        )
    );
    exit;
}

And, the JS code:

function jsonParse() {
    try {
        var json = JSON.parse(text);
    } 
    catch(e) {
        return false;
    }
    return json;
}

var http = new XMLHttpRequest();
var data = "username=" + name + '&email=' + email;

http.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var json = jsonParse(this.responseText);

        if (!json || json.status !== true) {
            console.log(json.error || 'Something Bad Happened');
            return;
        }    

        alert('Everything is Fine!');

    }
}

http.open('ajax.php', 'POST', true);
http.send(data);

Thanks.

  • 发表于 2019-03-05 13:37
  • 阅读 ( 85 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除