简体   繁体   中英

No response when using jQuery/AJAX with JSONP

I am trying to make a cross-domain request using jQuery/AJAX. I have the following code;

$.ajax({
   url: "http://www.cjihrig.com/development/jsonp/jsonp.php?callback=jsonpCallback&message=Hello",
   crossDomain:true
})
.done(function( msg ) {
  alert( "Done : " + msg );
})
.fail(function( msg) {
  alert( "Fail : " + msg);
})
.always(function( msg ) {
  alert( "Always : " + msg );
});

The URL http://www.cjihrig.com/development/jsonp/jsonp.php?callback=jsonpCallback&message=Hello returns JSON object when calling directly and works fine when using JSONP in traditional manner (ie through dynamic script tag injection)

But why do I get an error when using it with jQuery/AJAX ?

Try this code because the error isn't set the dataType and isn't expect a jsonp default
dataType: (default: Intelligent Guess (xml, json, script, or html))
Type: String

  $.ajax({
   url: "http://www.cjihrig.com/development/jsonp/jsonp.php?callback=jsonpCallback&message=Hello",
   dataType: 'jsonp',
   crossDomain:true,
    jsonp: false,
    success: jsonpCallback,
})
.done(function( msg ) {
  alert( "Done : " + msg );
})
.fail(function( msg) {
  alert( "Fail : " + msg);
})
.always(function( msg ) {
  alert( "Always : " + msg );
});

 function jsonpCallback(data){
        alert("jsonpCallback");
    }

DEMO

I would use $.ajax with the option:

dataType: "jsonp"

This automatcially adds the callback option to the url. http://api.jquery.com/jQuery.ajax/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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