Jquery ajax USES jsonp as a restriction solution

  • 2020-03-29 23:58:46
  • OfStack

Jsonp addresses the problem of cross-domain ajax calls. Why cross-domain ajax calls? This allows you to call another application's API (under a different domain name) directly from the front end of one application using js.
We also used jsonp in the practical application, but before we only knew a limit of jsonp, which can only send get requests. The disadvantage of get requests is that the request length is limited.
Today, another limitation of jsonp (in the case of jquery ajax) was discovered -- the error callback that does not trigger $. Ajax, with the following sample code:

    dataType: 'jsonp',            
    error: function (xhr) {
        //This callback function is not executed in the event of an error

This limitation is determined by the implementation mechanism of jsonp.


Use a jquery plugin - jquery - the json, https://github.com/jaubourg/jquery-jsonp

Sample code:

<script src="https://raw.github.com/jaubourg/jquery-jsonp/master/src/jquery.jsonp.js"></script>

    url: '',
    success: function (data) {
    error: function (xOptions, textStatus) {

When a jsonp request fails, such as a 404 error, the error callback function executes, printing the string "error".

Related articles: