2013-04-09 98 views
0

我正在使用以下腳本發送跨域ajax調用。通過Ajax跨域調用

$(document).ready(function() 
{ 
var uniqcod=$(".abc").attr('id'); 
$.ajax({ 
    url:'abc.com', 
    data:{uniId:uniqcod}, 
    dataType: 'jsonp', 
    jsonp: 'callback', 
    crossDomain: true, 
    jsonpCallback:"jsonpCallback", 
    success: function(result){}, 
    error: function() {console.log('Failed!'); 
    console.log(arguments); } 
    }); 

function jsonpCallback(data){ 
    document.getElementById(uniqcod).innerHTML=data.content; 
} 

}); 

但問題是這個腳本不會在jsoncallback函數中進行。每次我調用此函數時,它都會在控制檯中顯示失敗的消息。

+0

變化' 「jsonpCallback」''到jsonpCallback'記錯 – 2013-04-09 12:39:52

+0

確實的URL你打支持JSONP? – jbabey 2013-04-09 12:40:08

+0

嘗試刪除「jsonp:'回調',crossDomain:true,jsonpCallback:」jsonpCallback「,」我認爲你不需要它們。 – JackPoint 2013-04-09 12:46:00

回答

0

如果您請求的服務器發回CORS(跨源資源共享)標頭,則只能執行跨域請求。

如果它是一個你控制的服務器,那麼你只需要做出改變。

如果沒有,您需要通過服務器代理數據,您控制添加適當的標頭。

編輯:或者如果它是JSONP,那麼你需要確保你請求的服務器實際上支持JSONP。

+0

這不是問題。因爲(跨源資源共享)標頭也包含在我發送請求的服務器上。問題在我的代碼中。 – 2013-04-09 12:50:12

0

除非通過身份驗證,否則無法使用jQuery進行跨域調用。但是,您可以使用YQL(Yahoo Query Language)並進行一些調用並獲取xml,json格式的數據。

請看下面的例子。

function requestCrossDomain(site, callback) { 

    // If no url was passed, exit. 
    if (!site) { 
     alert('No site was passed.'); 
     return false; 
    } 

    // Take the provided url, and add it to a YQL query. Make sure you encode it! 
    var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + site + '"') + '&format=xml&callback=cbFunc'; 

    // Request that YSQL string, and run a callback function. 
    // Pass a defined function to prevent cache-busting. 
    $.getJSON(yql, cbFunc); 

    function cbFunc(data) { 
    // If we have something to work with... 
    if (data.results[0]) { 
     // Strip out all script tags, for security reasons. 
     // BE VERY CAREFUL. This helps, but we should do more. 
     data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, ''); 

     // If the user passed a callback, and it 
     // is a function, call it, and send through the data var. 
     if (typeof callback === 'function') { 
      callback(data); 
     } 
    } 
    // Else, Maybe we requested a site that doesn't exist, and nothing returned. 
    else throw new Error('Nothing returned from getJSON.'); 
    } 
} 
+0

我從兩端處理這個問題。我已經包含頭('內容類型:訪問控制允許來源:*'); header('content-type:Access-Control-Allow-Methods:GET'); header('content-type:text/javascript');在服務器上。但問題仍然是一樣的。 – 2013-04-09 12:51:41

+0

你會得到任何錯誤?如果是這樣,你能分享錯誤文本和錯誤狀態代碼嗎? – Harish 2013-04-09 13:31:31