dongpa3109 2012-01-24 00:12
浏览 116
已采纳

我可以使用PHP从JQuery AJAX请求返回输出状态吗?

I have an AJAX request (using JQuery) that calls a PHP script which does some database business. The request code is as follows:

$.ajax({
    url: "script.php",
    data: { value: value
        },
    type: 'post',
    success: function(output){
        alert(output);
    }
});

However, I wanted to see if there was a way to also (in addition to the unchanged output string) return a status. It can be as simple as an integer. The point is I want to disable a button (with Javascript) if the PHP script for any reason fails to connect to mySQL, but I still want the PHP scripts output exactly as it would be.

I tried the error option:

...
success: function(output){
        alert(output);
    },
error: function(output){
        // do something
    }

but I do not know how to make PHP display an error and continue on the rest of the script. Again, I don't want to tamper at all with the output string.

In pseudo-code, I'm looking for something like this:

$.ajax({
    url: "script.php",
    data: { value: value
        },
    type: 'post',
    success: function(output){
        if(output.status == 0){
            alert(output);
        }else{
            // do something else
        }
    }
});

Is anything of the sort possible? Thanks for any and all help!

  • 写回答

3条回答 默认 最新

  • douningchang3610 2012-01-24 01:25
    关注

    I usually return data from the server in JSON format. This way I can return as many different types of data as may be needed by the success function in javascript.

    basically in PHP you would do something like

    $response = new stdClass();
    $response->error = 'Could not connect to Mysql';
    $response->message = 'Some other text';
    echo json_encode($response);
    

    in JQuery, the ajax() method would automatically detect that the response is json and parse it into a javascript object, so you could access like this

    if (typeof response.error !== undefined) alert(response.error);
    

    for more on that look at dataType argument for the ajax() method in the jQuery documentation.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘