2013-04-09 248 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