Ajax Asynchronous Request 302

Source: Internet
Author: User



We know that only if the request is successful Ajax will be callback processing, the status code is state >= && status < 300 | | Status = = 304; This can be verified by looking at the source code of jquery.


// Cache response headers
responseHeadersString = headers || "";

// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;

// Determine if successful
isSuccess = status >= 200 && status < 300 || status === 304;// Determine if the request was successful.

// Get response data
If ( responses ) {
    Response = ajaxHandleResponses( s, jqXHR, responses );
}

// Convert no matter what (that way responseXXX fields are always set)
Response = ajaxConvert( s, response, jqXHR, isSuccess );

// If successful, handle type chaining
If ( isSuccess ) {

    // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
    If ( s.ifModified ) {
        Modified = jqXHR.getResponseHeader("Last-Modified");
        If ( modified ) {
            jQuery.lastModified[ cacheURL ] = modified;
        }
        Modified = jqXHR.getResponseHeader("etag");
        If ( modified ) {
            jQuery.etag[ cacheURL ] = modified;
        }
    }

    // if no content
    If ( status === 204 || s.type === "HEAD" ) {
        statusText = "nocontent";

    // if not modified
    } else if ( status === 304 ) {
        statusText = "notmodified";

    // If we have data, let‘s convert it
    } else {
        statusText = response.state;
        Success = response.data;
        Error = response.error;
        isSuccess = !error;
    }
} else {
    // We extract error from statusText
    // then normalize statusText and status for non-aborts
    Error = statusText;
    If ( status || !statusText ) {
        statusText = "error";
        If ( status < 0 ) {
            Status = 0;
        }
    }
}

  For example, using AJAX to implement redirection, Ajax asynchronous requests a,a internal redirection to B.



Thinking:



Will the Q1:ajax callback method be executed?



Can q2:ajax redirect?


Var mobile = $("input[name=‘mobile‘]").val();
$.post("/recharge/pay", {mobile:mobile}, function(backData) {
     Alert("execute callback");
     Alert(backData);
}).complete(function(xhr) {
     Alert("Request Status Code:"+xhr.status);
});

@RequestMapping(value = "/recharge/m{mobile}",method = RequestMethod.GET) public String rechargeB(@PathVariable String mobile, ModelMap model){
    model.put("mobile",mobile); return "user/recharge";
}

@RequestMapping(value = "/recharge/pay",method = RequestMethod.POST) public String rechargeA(String mobile){
    String rechargeUrl = "/recharge/m19012345678"; return "redirect:"+rechargeUrl;
}


After the test found that the callback method can be executed normally, the return status code is also 200, here is how to execute it exactly? First, after the Ajax POST request to the/recharge/pay, the A method internally redirects, this time the status code returned should be 302, and secondly, after a redirect to B, the execution of the completion of the returned status code should be 200, the callback method is executed after the execution of B. It can be confirmed by the network of Google Chrome.









  This question can be referred to an answer on the StackOverflow.


You can ' t handle redirects with XHR callbacks because the browser takes care of them automatically. You'll only get back to the redirected location.


It turns out that when the server sends a 302 response to the browser, the browser does not directly perform the AJAX callback processing, but instead performs a 302 redirect-reading the location information from the response headers and then making a request to the URL in the location. The Ajax callback is not processed until the response to this request is received. the approximate process is as follows:



Ajax Browser, 302, browser (redirect), server, browser, Ajax



In our test program, because the redirect URL returned by 302 has a corresponding handler on the server, the status code obtained in the AJAX callback function is 200.



So, if you want to redirect through Location.href in an AJAX request based on a 302 response, it's not feasible.



When testing, note that if you specify the 4th parameter of the AJAX datatype (the data type expected from the server), the callback method may not be triggered because the redirect is performed first, that is, the redirected content responds as an Ajax interface content. While debugging, you can also see that the content of Backdata is not a JSON string, but rather an HTML string redirected to page B. In fact, the process of the test example itself has a problem, the address of the AJAX request should only return data, not redirect.



Another thing to note is that the GET, post is encapsulated on the basis of Ajax, only encapsulated success, and does not encapsulate the error method, so as long as the request returned by the status code is not 200-300, will not go back to the callback method, see source code.


jQuery.each( [ "get", "post" ], function( i, method ) {
     jQuery[ method ] = function( url, data, callback, type ) {
         // shift arguments if data argument was omitted
         If ( jQuery.isFunction( data ) ) {
             Type = type || callback;
             Callback = data;
             Data = undefined;
         }

         Return jQuery.ajax({
             Url: url,
             Type: method,
             dataType: type,
             Data: data,
             Success: callback // only encapsulates the success method, no error.
         });
     };
});  




Summarize:



1, Ajax is mainly used for asynchronous request data, rather than redirection, it is only responsible for obtaining data or processing results;



2, only the status code status>=200 && status<300 | | status==304, only be regarded as success, only then will go success callback method;



3, post, get only encapsulates the Ajax success method.





Reference documents attached


    • Cannot handle 302 redirect in Ajax and why?

    • Ajax with 302 response

    • JQuery Ajax 302 Cross-domain
    • Jquery-1.11.2.js Source





Ajax Asynchronous Request 302


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.