通过PHP中的AJAX回显数据

时间:2022-08-19 16:56:12

I have just started coding in PHP. I previously worked in asp.net. In do net webmethod you return the data neatly to AJAX call. Trying in PHP I found that you at best can just echo the data you want to return.

我刚开始用PHP编写代码。我以前在asp.net工作过。在do net webmethod中,您可以将数据整齐地返回给AJAX调用。试用PHP我发现你最多只能回显你想要返回的数据。

If I convert the data to JSON on server and then return then it not sure PHP will not encode the error messages into it. That creates invalid JSON in client side code and the results are not possible to parse.

如果我将数据转换为服务器上的JSON然后返回,那么它不确定PHP不会将错误消息编码到其中。这会在客户端代码中创建无效的JSON,并且无法解析结果。

So I want to know if there is something advanced I can do to always return neatly and nicely from the server, even when an error occurs?

因此,我想知道是否有一些先进的功能,即使发生错误,也能始终从服务器上整齐地返回?

Clarification: first when error occurs then decoding on the client from JSON is not possible. This is the question, actually.

澄清:首先发生错误,然后从JSON在客户端解码是不可能的。实际上,这就是问题所在。

2 个解决方案

#1


It seems like the basis of this problem is an unhandled exception on the server, which will upset your JSON output with invalid strings (or, if error reporting is turned off as it should be, the JSON output will be unfinished, and thus still invalid).

似乎此问题的基础是服务器上的未处理异常,这将使用无效字符串扰乱您的JSON输出(或者,如果错误报告关闭应该是,JSON输出将未完成,因此仍然无效)。

Consider this AJAX code:

考虑这个AJAX代码:

function getPost()
{
    return riskyOperation(); // throws \PDOException
}

echo json_encode(getPost());

That is obviously going to cause problems in the event of a database error. To fix it, you could do something like this:

这显然会在数据库错误的情况下引起问题。要修复它,你可以这样做:

function getPost()
{
    try
    {
        $post = riskyOperation(); // throws \PDOException
    }
    catch (\PDOException $e)
    {
        // @todo Log the exception here
        $post = ['error' => 'A database error occurred', ];
    }

    return $post;
}

echo json_encode(getPost());

Notice in this case I am not sending the error message to the client (in $e->getMessage()) since technical errors about the database are not appropriate for users, and may assist cracking attempts.

请注意,在这种情况下,我不会将错误消息发送到客户端(在$ e-> getMessage()中),因为有关数据库的技术错误不适合用户,并且可能有助于破解尝试。

Also, it's worth programming defensively too - rather than running code that might throw an error, it is often possible to make checks prior to running that code, so that an error can be avoided instead of caught.

此外,值得进行防御性编程 - 而不是运行可能引发错误的代码,通常可以在运行该代码之前进行检查,以便可以避免错误而不是捕获错误。

#2


Yes, You can echo the data in json data structure from php. Here is example

是的,您可以从php回显json数据结构中的数据。这是一个例子

PHP

$data = array( 'name' => 'David' , 'age' => '25' );
header('Content-Type: application/json');
echo json_encode($data); //Convert array to json string

Javascript (Client Side)

Javascript(客户端)

  var data = { 'var' : '123' }; // Some data if you want to send to server

    $.ajax({

    url: "PATH_TO_PHP_FILE", 
    data : data, 
    dataType: "json",

    success: function(json){

    var response=jQuery.parseJSON(json);

    if(typeof response =='object') {

    alert(json.name);
    alert(json.age);

    } else {        
    echo "Not valid json object";
    }

    }

    });

#1


It seems like the basis of this problem is an unhandled exception on the server, which will upset your JSON output with invalid strings (or, if error reporting is turned off as it should be, the JSON output will be unfinished, and thus still invalid).

似乎此问题的基础是服务器上的未处理异常,这将使用无效字符串扰乱您的JSON输出(或者,如果错误报告关闭应该是,JSON输出将未完成,因此仍然无效)。

Consider this AJAX code:

考虑这个AJAX代码:

function getPost()
{
    return riskyOperation(); // throws \PDOException
}

echo json_encode(getPost());

That is obviously going to cause problems in the event of a database error. To fix it, you could do something like this:

这显然会在数据库错误的情况下引起问题。要修复它,你可以这样做:

function getPost()
{
    try
    {
        $post = riskyOperation(); // throws \PDOException
    }
    catch (\PDOException $e)
    {
        // @todo Log the exception here
        $post = ['error' => 'A database error occurred', ];
    }

    return $post;
}

echo json_encode(getPost());

Notice in this case I am not sending the error message to the client (in $e->getMessage()) since technical errors about the database are not appropriate for users, and may assist cracking attempts.

请注意,在这种情况下,我不会将错误消息发送到客户端(在$ e-> getMessage()中),因为有关数据库的技术错误不适合用户,并且可能有助于破解尝试。

Also, it's worth programming defensively too - rather than running code that might throw an error, it is often possible to make checks prior to running that code, so that an error can be avoided instead of caught.

此外,值得进行防御性编程 - 而不是运行可能引发错误的代码,通常可以在运行该代码之前进行检查,以便可以避免错误而不是捕获错误。

#2


Yes, You can echo the data in json data structure from php. Here is example

是的,您可以从php回显json数据结构中的数据。这是一个例子

PHP

$data = array( 'name' => 'David' , 'age' => '25' );
header('Content-Type: application/json');
echo json_encode($data); //Convert array to json string

Javascript (Client Side)

Javascript(客户端)

  var data = { 'var' : '123' }; // Some data if you want to send to server

    $.ajax({

    url: "PATH_TO_PHP_FILE", 
    data : data, 
    dataType: "json",

    success: function(json){

    var response=jQuery.parseJSON(json);

    if(typeof response =='object') {

    alert(json.name);
    alert(json.age);

    } else {        
    echo "Not valid json object";
    }

    }

    });