2017-09-09 23 views
1

我想打電話給這個Instagram網站,返回用戶信息:https://www.instagram.com/therock/?__a=1,所以這就是爲什麼我使用JSONP而不是JSON來避免CORS問題。JSONP致電Instagram的網絡返回未捕獲的SyntaxError:意外的令牌:

這是我做的基礎上,回答a question asked here

<script> 
    $(document).ready(function(){ 
     $.ajax({ 
      url: 'https://www.instagram.com/therock/?__a=1', 
      dataType: 'jsonp', 
      jsonpCallback: 'callback', 
      type: 'GET', 
      success: function (data) { 
       console.log(data); 
      } 
     }); 
    }) 
</script> 

我也試圖改變這一號召:

$.ajax({ 

     url: "https://www.instagram.com/therock/?__a=1", 
     type: "POST", 
     jsonpCallback: 'jsonpCallback', 
     dataType: "jsonp", 
     success: function (result) { 
      console.log(result) 

     }, 

    }); 

我使用JSONP沒有Ajax終於嘗試:

var $jsonp = (function(){ 
    var that = {}; 

    that.send = function(src, options) { 
    var callback_name = options.callbackName || 'callback', 
     on_success = options.onSuccess || function(){}, 
     on_timeout = options.onTimeout || function(){}, 
     timeout = options.timeout || 10; // sec 

    var timeout_trigger = window.setTimeout(function(){ 
     window[callback_name] = function(){}; 
     on_timeout(); 
    }, timeout * 1000); 

    window[callback_name] = function(data){ 
     window.clearTimeout(timeout_trigger); 
     on_success(data); 
    } 

    var script = document.createElement('script'); 
    script.type = 'text/javascript'; 
    script.async = true; 
    script.src = src; 

    document.getElementsByTagName('head')[0].appendChild(script); 
    } 

    return that; 
})(); 

並且調用這樣的函數,但不幸的是總是返回超時

$jsonp.send('https://www.instagram.com/therock/?__a=1?callback=handleStuff', { 
    callbackName: 'handleStuff', 
    onSuccess: function(json){ 
     console.log('success!', json); 
    }, 
    onTimeout: function(){ 
     console.log('timeout!'); 
    }, 
    timeout: 5 
}); 

我已經嘗試過很多的可能性,同時尋找在這裏的StackOverflow或谷歌搜索將JSONP沒有不同問題的工作。非常感謝任何幫助,提前感謝。

+1

服務器仍然需要返回JSONP才能正常工作。 [請參閱此答案以獲取更多信息](https://stackoverflow.com/a/21715747/1848744)。有一個原因是您無法從不會用作外部API端點的URL中獲取數據。您的替代方案將使用Web服務器作爲獲取這些結果的代理。 –

+0

這裏的教訓是 - 你不能擊敗CORS –

+0

感謝Matt,你對服務器返回是正確的,我截獲了請求,並且看到它被髮送到服務器並收到響應,唯一的問題是變量'data'或'result'由於錯誤而不包含該響應。 –

回答

0

我認爲你的JSONP url響應數據不是標準的jsonp數據格式。它是一個純json格式,即打開頁面後總會得到js錯誤。您可以嘗試將url響應數據修改爲標準jsonp格式,右邊是JSONP_CALLBACK_FUNCTION(JSON字符串數據)

+0

是否意味着將'function(data)'改爲'jsonp_callback_function(data )'? –

+0

不,您需要修改程序代碼中的返回值,而不是js。 – Lane

+0

你可以看到[answer](https://stackoverflow.com/questions/3839966/can-anyone-explain-what-jsonp-is-in-layman-terms),你會知道JSON和JSONP之間的區別 – Lane

相關問題