1 function crossDomainAjax(url, successCallback) { 2 3 // IE8 & 9 only Cross domain JSON GET request 4 if ('XDomainRequest' in window && window.XDomainRequest !== null) { 5 6 var xdr = new XDomainRequest(); // Use Microsoft XDR 7 xdr.open('get', url); 8 xdr.onload = function () { 9 var dom = new ActiveXObject('Microsoft.XMLDOM'), 10 JSON = $.parseJSON(xdr.responseText); 11 12 dom.async = false; 13 14 if (JSON == null || typeof (JSON) == 'undefined') { 15 JSON = $.parseJSON(data.firstChild.textContent); 16 } 17 18 successCallback(JSON); // internal function 19 }; 20 21 xdr.onerror = function () { 22 _result = false; 23 }; 24 25 xdr.send(); 26 } 27 28 // IE7 and lower can't do cross domain 29 else if (navigator.userAgent.indexOf('MSIE') != -1 && 30 parseInt(navigator.userAgent.match(/MSIE ([d.]+)/)[1], 10) < 8) { 31 return false; 32 } 33 34 // Do normal jQuery AJAX for everything else 35 else { 36 $.ajax({ 37 url: url, 38 cache: false, 39 dataType: 'json', 40 type: 'GET', 41 async: false, // must be set to false 42 success: function (data, success) { 43 successCallback(data); 44 } 45 }); 46 } 47 }
执行回调方法
1 crossDomainAjax(url, function (data) { 2 3 var newdata = data.Content; 4 var str = ""; 5 for (var i = 0; i < newdata.length; i++) { 6 str += '<li><a href="http://www.XXX.com/Crawler.aspx?purl=' + encodeURI(newdata[i].Producturl) + '" target="_blank"><div><img src="' + newdata[i].img + '"alt=""/></div><p>' + newdata[i].Name + '</p></a><p class="red">¥' + newdata[i].pric + '</p></li> '; 7 } 8 if (data.img != "" && data.img != null) { 9 $(".banner img").attr("src", data.img) 10 } else { 11 $(".banner").hide(); 12 } 13 document.title = data.title + '- Panli代购'; 14 callback(parseInt(data.Count)); 15 $(".content ul").html(str); 16 });