跨域$ .ajax

时间:2012-09-16 11:31:22

标签: jquery ajax jsonp

UPDATE 目前我除了调整工作代码外什么都没收到。 这个逻辑出了什么问题? 我使用dataType:'jsonp'进行$ .ajax调用,因为它是跨域调用的唯一方法。 我知道,该调用需要'jsonp'类型,而是接收'text / html'。如何解析此响应(转换,预处理,过滤)?

谢谢!

这是一个问题。 我只想尝试使用jSON。 这是有效的。

$(document).ready(function(){
    $('ul li a').click(function (){
    var test = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="www.mohtasebi.com/blog/2011/06/cross-domain-ajax-using-jquery-the-ultimate-guide/"') + '&format=xml&callback=?';
  //var test = "http://mohtasebi.com/blog/2011/06/cross-domain-ajax-using-jquery-the-ultimate-guide/";
    loadPage(test);
    });
});

function loadPage(test)
{
    $.ajax({
    url:test,
    dataType:'jsonp',
    crossDomain: 'true',
    success: function(data){    
    if ( data.results[0] ) {     
    alert("ok")
    } }
});

}

但如果我使用评论网址

  

var test =   “http://mohtasebi.com/blog/2011/06/cross-domain-ajax-using-jquery-the-ultimate-guide/”;

而非YUI converted我收到此错误:

  

资源解释为脚本但以MIME类型传输   为text / html:   “http://mohtasebi.com/blog/2011/06/cross-domain-ajax-using-jquery-the-ultimate-guide/?callback=jQuery18104882542605046183_1347794498881&_=1347794500464”。   jquery.min.js:8169 Uncaught SyntaxError:意外的令牌<   mohtasebi.com:1

我做错了什么。谢谢!

2 个答案:

答案 0 :(得分:2)

var test = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="www.mohtasebi.com/blog/2011/06/cross-domain-ajax-using-jquery-the-ultimate-guide/"') + '&format=xml';

$.ajax({
    url: test,
    dataType: 'jsonp',
    jsonpCallback: 'blah',  // just add this and remove &callback=? from url last
    crossDomain: 'true',
    success: function(data) {
        console.log(data);  // see the console for data
        if (data.results[0]) {
            alert('OK');
        }
    }
});​

jsonpCallback添加到a​​jax配置并删除& callback =?来自网址的最后一部分。

Demo

答案 1 :(得分:0)

使用$.getJSON,这要简单得多。

var test = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="www.mohtasebi.com/blog/2011/06/cross-domain-ajax-using-jquery-the-ultimate-guide/"') + '&format=xml&callback=?';
$.getJSON(test, function (data) {
  console.log(data);
});

The demo.