如何获取JSONP数据

时间:2013-06-07 14:11:44

标签: javascript jquery json jsonp

我在外部域上有一个文件,其格式如下:

{"image":"http:\/\/magazine.domain.com\/wp-content\/uploads\/2013\/06\/festival_home-240x122.jpg","link":"http:\/\/magazine.domain.com\/category\/fashion\/forget-the-mud-festival-fashion-essentials\/","title":"FESTIVAL FASHION ESSENTIALS","description":"What to wear at festivals is a perennial problem for music lovers, follow our fashion guide and be the best dressed moshing in the mud this summer!"}

我需要使用JSONP获取数据并将格式更改为:

jsonCallback ({"image":"http:\/\/magazine.domain.com\/wp-content\/uploads\/2013\/06\/festival_home-240x122.jpg","link":"http:\/\/magazine.domain.com\/category\/fashion\/forget-the-mud-festival-fashion-essentials\/","title":"FESTIVAL FASHION ESSENTIALS","description":"What to wear at festivals is a perennial problem for music lovers, follow our fashion guide and be the best dressed moshing in the mud this summer!"});

我正在使用jquery 1.3.2,我暂时无法升级,并尝试了以下内容:

var url='http://magazine.domain.com/test1.js?callback=?';

$.getJSON(url, function(data){
 console.log(data);
});

我收到以下错误 - 未捕获的ReferenceError:未定义jsonCallback。

有人可以帮忙吗。

2 个答案:

答案 0 :(得分:0)

您需要将jsonCallback替换为callback查询字符串参数的值。

答案 1 :(得分:0)

var url='http://magazine.domain.com/test1.js';

$.ajax({
    url: url,
    dataType: 'jsonp', // <-- jsonp
    success: function(resp) {
        // resp == {"image":"http:\/\/magazine.domain.com\/wp-content\/uploads\/2013\/06\/festival_home-240x122.jpg","link":"http:\/\/magazine.domain.com\/category\/fashion\/forget-the-mud-festival-fashion-essentials\/","title":"FESTIVAL FASHION ESSENTIALS","description":"What to wear at festivals is a perennial problem for music lovers, follow our fashion guide and be the best dressed moshing in the mud this summer!"}
    }
});