解析json时出错

时间:2013-11-30 12:23:31

标签: javascript html json

以下是解析从api收到的json文件的代码。但解析后它没有显示任何输出,

var codingAPI = "http://glosbe.com/gapi/translate from=eng&dest=hin&format=json&phrase=boy";

$.getJSON(codingAPI, function (json) {

    // Set the variables from the results array
    var address = json.tuc[0].pharse.language;

    $('#address').text(address);

});

// Caching the link jquery object
var $myLink = $('a.myLink');

// Set the links properties
$myLink.prop({
    href: codingAPI,
    title: 'Click on this link to open in a new window.'
}).click(function (e) {
    e.preventDefault();
    window.open(this.href, '_blank');
});

代码放在jsfiddle

2 个答案:

答案 0 :(得分:3)

这是由于相同的原产地政策。

查看控制台错误

  

XMLHttpRequest无法加载http://glosbe.com/gapi/translate?from=eng&dest=hin&format=json&phrase=boy。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许原点“http://fiddle.jshell.net”访问。

答案 1 :(得分:1)

由于不允许对此文件进行跨源请求,因此您可以使用JSONP - 服务器支持它。使用jQuery,您只需使用?callback=?即可使响应成功。

var codingAPI = "http://glosbe.com/gapi/translate?from=eng&dest=hin&format=json&phrase=boy&callback=?";

$.getJSON(codingAPI, function (json) {

    // Set the variables from the results array
    var address = json.tuc[0].phrase.language;

    $('#address').text(address);

});

// Caching the link jquery object
var $myLink = $('a.myLink');

// Set the links properties
$myLink.prop({
    href: codingAPI,
    title: 'Click on this link to open in a new window.'
}).click(function (e) {
    e.preventDefault();
    window.open(this.href, '_blank');
});

此外,您在回调函数中错误phrasepharse