duan33360 2014-10-02 16:25
浏览 27
已采纳

用ajax回答错误请求时读取json结果

I'd like to send an error to the user via ajax, if he don't fill the form properly.

This is how I send the answer to the browser via ajax:

if($bo){
    header('HTTP/1.1 400 Bad Request');
    header('Content-Type: application/json; charset=UTF-8');
    $error['message'] = 'Some error message';
    echo json_encode($error);
    die;
}

And this is my jquery script:

$.ajax(
            {
                url: formURL,
                type: "POST",
                data: postData,
                success: function(data, textStatus, jqXHR)
                {

                    // some code ...

                },
                error: function(data, jqXHR, textStatus, errorThrown)
                {
                    // how to get message here json{"message":"some_message"}
                    var jsonObj = JSON.parse(data);
                    $r = jsonObj.message;
                    alert($r);                    
               }
            });

I can see the message using firebug console but I don't know how to get the variable containing my error :/

Any suggestion please?

Thanks

  • 写回答

2条回答 默认 最新

  • dou4381 2014-10-02 18:29
    关注

    Thanks everybody.

    I guess I've found the solution. To access message value:

    error: function(data, jqXHR, textStatus, errorThrown) 
            {
                console.log(data.responseJSON.message);
            }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度