-.
Zepto, jQuery, , jQuery.
, -:
$.ajax({
url: url,
type: 'GET',
dataType: 'jsonp',
contentType: 'application/x-javascript',
crossDomain: true,
success: function (data, status) { }
error: function () { }
$. ajax $. ajaxJSONP crossdomain. Zepto $. AjaxJSONP:
$.ajaxJSONP = function(options){
var callbackName = 'jsonp' + (++jsonpID),
script = document.createElement('script'),
abort = function(){
$(script).remove()
if (callbackName in window) window[callbackName] = empty
ajaxComplete('abort', xhr, options)
},
xhr = { abort: abort }, abortTimeout
if (options.error) script.onerror = function() {
xhr.abort()
options.error()
}
window[callbackName] = function(data){
clearTimeout(abortTimeout)
$(script).remove()
delete window[callbackName]
ajaxSuccess(data, xhr, options)
}
serializeData(options)
script.src = options.url.replace(/=\?/, '=' + callbackName)
$('head').append(script)
if (options.timeout > 0) abortTimeout = setTimeout(function(){
xhr.abort()
ajaxComplete('timeout', xhr, options)
}, options.timeout)
return xhr
}
My workaround is very simple and consists of an interval called several times in the script.onload event handler to check if the callback function has been called.
This is my version of the $ function . ajaxJSONP :
$.ajaxJSONP = function(options){
var called = false,
callbackName = 'jsonp' + (++jsonpID),
script = document.createElement('script'),
abort = function(){
$(script).remove()
if (callbackName in window) window[callbackName] = empty
ajaxComplete('abort', xhr, options)
},
xhr = { abort: abort }, abortTimeout
if (options.error) {
script.onerror = function() {
xhr.abort()
options.error()
};
script.onload = function () {
var times = 0;
var interval = setInterval(function () {
if (times++ == 5) {
clearInterval(interval);
if (!called) {
options.error();
}
} else if (called) {
clearInterval(interval);
}
}, 100);
};
}
window[callbackName] = function(data){
called = true;
clearTimeout(abortTimeout)
$(script).remove()
delete window[callbackName]
ajaxSuccess(data, xhr, options)
}
serializeData(options)
script.src = options.url.replace(/=\?/, '=' + callbackName)
$('head').append(script)
if (options.timeout > 0) abortTimeout = setTimeout(function(){
xhr.abort()
ajaxComplete('timeout', xhr, options)
}, options.timeout)
return xhr
}
Note. If you are interested in server-side behavior, see the beginning of this guide: http://phonegap.com/2011/07/20/making-jsonp-calls-with-zepto-on-android-device/