2013-04-26 31 views
-1

如何將這個jquery函數重寫爲常規javascript?如何將jquery重寫爲javascript:JsonP +回調

$(document).ready(function() { 
    $.ajax({ 
     url: 'http://192.168.1.103:8124/', 
     dataType: "jsonp", 
     jsonpCallback: "_testcb", 
     cache: false, 
     timeout: 5000, 
     success: function(data) { 
      $("#test").append(data); 
     }, 
     error: function(jqXHR, textStatus, errorThrown) { 
      alert('error ' + textStatus + " " + errorThrown); 
     } 
    }); 
}); 

特別

jsonpCallback: "_testcb", 
     cache: false, 

原始錯誤的問題: 如何一組一個XMLHttpRequest對象的屬性,使用常規的JavaScript收到JSONP回調?

更新了正確的問題: 如何使用「純Javascript」製作JsonP回調?

+1

Stackoverflow不是一個代碼轉換工具。你有特別的問題嗎? – zerkms 2013-04-26 00:21:15

+0

搜索:http://stackoverflow.com/questions/8567114/how-to-make-an-ajax-call-without-jquery – tymeJV 2013-04-26 00:23:07

+0

這是更多關於採用上述jquery函數設置的屬性...我會舉一個例子。 – FredTheWebGuy 2013-04-26 00:23:37

回答

3

發送一個請求,看看它是什麼樣子,通過瀏覽器的Web開發工具:

enter image description here

所以模仿jQuery的防緩存行爲,你可以在發送時添加時間戳參數的URL AJAX請求:

jsonp(url + '&_=' + (new Date).getTime()); 

對於JSONP回調,你只是傳遞一個callback參數:

jsonp(url + '?callback=' + callback_name); 

然後瀏覽器基本上調用eval(callback_name + '(' + response + ')');,所以請確保您的回調函數是全局的。

+0

啊哈!一個回調參數... – FredTheWebGuy 2013-04-26 00:29:50

+0

是上面示例中的jsonpCallback:「_testcb」嗎? – FredTheWebGuy 2013-04-26 00:30:25

+0

@DudeSolutions:是的,看我的截圖。這可能有點難以閱讀,但jQuery源文件不是太複雜:https://github.com/jquery/jquery/blob/master/src/ajax/jsonp.js – Blender 2013-04-26 00:30:42

0

更新:

那麼一點點的挖掘後,我發現了相當於從這個post

function foo(data) 
{ 
    // do stuff with JSON 
} 

var script = document.createElement('script'); 
script.src = '//example.com/path/to/jsonp?callback=foo' 

document.getElementsByTagName('head')[0].appendChild(script); 
// or document.head.appendChild(script) in modern browsers 

就像一個魅力!