简体   繁体   English

jQuery Ajax - 如何获取错误的响应数据

[英]jQuery Ajax - how to get response data in error

I have a simple web application. 我有一个简单的Web应用程序。 I've created the server REST API so it will return a response with HTTP code and a JSON (or XML) object with more details: application code (specific to scenario, message that describe what happened etc.). 我已经创建了服务器REST API,因此它将返回带有HTTP代码的响应和带有更多详细信息的JSON(或XML)对象:应用程序代码(特定于场景,描述发生的事件的消息等)。

So, for example if a client send a Register request and the password is too short, the response HTTP code will be 400 (Bad Request), and the response data will be: {appCode : 1020 , message : "Password is too short"} . 因此,例如,如果客户端发送注册请求且密码太短,则响应HTTP代码将为400(错误请求),响应数据将为: {appCode : 1020 , message : "Password is too short"}

In jQuery I'm using the "ajax" function to create a POST request. 在jQuery中,我使用“ajax”函数来创建POST请求。 When the server returns something different from HTTP code 200 (OK), jQuery defines it as "error". 当服务器返回与HTTP代码200(OK)不同的内容时,jQuery将其定义为“错误”。

The error handler can get 3 parameters: jqXHR, textStatus, errorThrown. 错误处理程序可以获得3个参数:jqXHR,textStatus,errorThrown。 Ho can I get the JSON object that sent by the server in error case? 我可以在错误的情况下获取服务器发送的JSON对象吗?

Edit: 编辑:

1) Here is my JS code: 1)这是我的JS代码:

function register (userName, password) {
    var postData = {};
    postData["userName"] = userName;
    postData["password"] = password;

    $.ajax ({
        dataType: "json",
        type: "POST",
        url: "<server>/rest/register",
        data: postData,
        success: function(data) {
            showResultSucceed(data);
            hideWaitingDone();
        },
        error: function (jqXHR, textStatus, errorThrown) {

            showResultFailed(jqXHR.responseText);
            hideWaitingFail();
        }
    })
}

2) When looking at Firebug console, it seems like the response is empty. 2)在查看Firebug控制台时,响应似乎是空的。 When invoking the same request by using REST testing tool, I get a response with JSON object it it. 当使用REST测试工具调用相同的请求时,我得到了一个带有JSON对象的响应。

What am I doing wrong? 我究竟做错了什么?

Here's an example of how you get JSON data on error: 以下是如何获取有关错误的JSON数据的示例:

$.ajax({
    url: '/path/to/script.php',
    data: {'my':'data'},
    type: 'POST'
}).fail(function($xhr) {
    var data = $xhr.responseJSON;
    console.log(data);
});

From the docs : 来自文档

If json is specified, the response is parsed using jQuery.parseJSON before being passed, as an object, to the success handler. 如果指定了json,则在作为对象传递给成功处理程序之前,使用jQuery.parseJSON解析响应。 The parsed JSON object is made available through the responseJSON property of the jqXHR object. 解析的JSON对象通过jqXHR对象的responseJSON属性提供。

Otherwise, if responseJSON is not available, you can try $.parseJSON($xhr.responseText) . 否则,如果responseJSON不可用,您可以尝试$.parseJSON($xhr.responseText)

directly from the docs 直接来自文档

The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser's native XMLHttpRequest object. 自jQuery 1.5起,$ .ajax()返回的jQuery XMLHttpRequest(jqXHR)对象是浏览器的本机XMLHttpRequest对象的超集。 For example, it contains responseText and responseXML properties, as well as a getResponseHeader() 例如,它包含responseText和responseXML属性,以及getResponseHeader()

so use the jqXRH argument and get the responseText property off it. 所以使用jqXRH参数并从中获取responseText属性。

In the link above, look for the section entitled 在上面的链接中,查找标题为的部分

The jqXHR Object jqXHR对象

I also faced same problem when i was using multipart/form-data. 当我使用multipart / form-data时,我也遇到了同样的问题。 At first I thought multipart/form-data created this mess, but later i found the proper solution. 起初我认为multipart / form-data创造了这个混乱,但后来我找到了正确的解决方案。

1) JS code before: 1)之前的JS代码:

var jersey_url = "http://localhost:8098/final/rest/addItem/upload";
var ans = $.ajax({
    type: 'POST',
    enctype: 'multipart/form-data',
    url: jersey_url,
    data: formData,
    dataType: "json",
    processData: false,
    contentType: false 
    success : funtion(data){
      var temp = JSON.parse(data);
      console.log("SUCCESS : ", temp.message);  
    }
    error : funtion($xhr,textStatus,errorThrown){
       console.log("ERROR : ", errorThrown);
       console.log("ERROR : ", $xhr);
       console.log("ERROR : ", textStatus);
    }
    });

Here when error occurred, it showed me this in console :- 在发生错误时,它在控制台中显示了这个: -
Error : 错误:
Error : { abort : f(e), always : f(), .... , responseJSON :"{"message":"failed"}" } 错误:{abort:f(e),always:f(),....,responseJSON:“{”message“:”failed“}”}
Error : error 错误:错误

Thus i came to know that we have to use $xhr.responseJSON to get the string message which we sent from rest api. 因此我开始知道我们必须使用$ xhr.responseJSON来获取我们从rest api发送的字符串消息。

2) modified/working error funtion: 2)修改/工作错误功能:

error : funtion($xhr,textStatus,errorThrown){
        var string= $xhr.responseJSON;
        var json_object= JSON.parse(string);
        console.log("ERROR : ",  json_object.message);
    }

Thus will output "Error : failed" on console. 因此将在控制台上输出“Error:failed”

After spending so much time on this problem, I found the problem. 在这个问题上花了这么多时间后,我发现了问题。

The page is under the URL: www.mydomain.com/register 该页面位于以下URL:www.mydomain.com/register
The REST api is under the URL: server.mydomain.com/rest REST api位于URL:server.mydomain.com/rest下

Seems like this kind of POST is not so simple. 好像这种POST并不那么简单。
I'm going to search more information to understand this issue better (if you have more information please share it with me). 我将搜索更多信息以更好地了解此问题(如果您有更多信息,请与我分享)。

When putting the REST API under www.mydomain.com/rest - everything is working fine. 将REST API放在www.mydomain.com/rest下 - 一切正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM