【问题标题】:jQuery Ajax Request to get JSON data fires error event获取 JSON 数据的 jQuery Ajax 请求触发错误事件
【发布时间】:2013-03-05 11:39:09
【问题描述】:

我正在尝试向 Google API 发出 ajax 请求,以获取当前汇率的 JSON 数据。

到目前为止我的代码:

$.ajax({
    url: "http://www.google.com/ig/calculator?hl=de&q=1USD=?EUR"
}).done( function ( data ) {
    var obj = $.parseJSON( data )
    alert( data.rhs );
});

google api 的链接是http://www.google.com/ig/calculator?hl=de&q=1USD=?EUR

我的问题是我的代码没有触发 done 函数。

我知道缺少一些东西,也许是一些参数?


更新

这是我在某处找到的新代码:

    function forex(val, from, to, callback) {
        $.ajax({
            url: 'http://www.google.com/ig/calculator?hl=en&q='+val+from+'%3D%3F'+to,
            type: 'GET',
            datatype: 'string',
            success: function(data) {
                var json = eval("(" + data+ ")"), output;
                if (typeof json == 'object' && json.rhs) {
                    output = json.rhs.match(/[0-9.\s]+/ig);
                    output = output[0] || false;
                } else {
                    output = data.match(/[0-9.\s]+/ig);
                    output = output[1] || false;
                }
                output = (output !== false) ? Number(output.replace(/\s/,'')) : output;
                callback(output);
            },
            error: function() {
                callback(false);
            }
        });
    }

    function output(data) {
        alert( data );
        $('#show_product_price_api').val(data);   
    }

但是当我使用这个功能时:

forex(100, 'USD', 'EUR', output);

要触发事件,我会收到“FALSE”回调

知道为什么调用这个错误函数吗??


更新 2

我认为这是一个跨域问题,有人对使用 jsonp 有任何建议吗?

【问题讨论】:

  • 你看ajax的文档了吗?
  • 我做了,但我很困惑
  • dataType:"json" 丢失。
  • 使用 $.getJson 可能会有所帮助
  • @Ace 你是从 ajax 中指定的 url 返回 json 吗?

标签: jquery ajax json request


【解决方案1】:

代码很好。 看看http://www.google.com/ig/calculator?hl=de&q=1USD=?EUR 的回复。

它不是一个有效的 JSON 字符串。所以它不会进入完成状态。

回复是{lhs: "1 US-Dollar",rhs: "0,767165324 Euro",error: "",icc: true} It should be {"lhs": "1 US-Dollar","rhs": "0,767165324 Euro","error": "","icc": true}

已编辑:

$.ajax({
    url: "http://www.google.com/ig/calculator?hl=de&q=1USD=?EUR"
}).done( function ( data ) {
    data = data.replace(/([a-z0-9]+):/gi,"\"$1\":"));
    var obj = $.parseJSON( data )
    alert( data.rhs );
});

【讨论】:

  • 好的,第 4 行有语法错误(双右括号)
  • 我仍然没有收到警报:
  • 能否在解析为 JSON 之前提醒数据并在此处发布。这对我有帮助。
  • 使用您从 URL 获得的响应来编辑您的问题。
  • 我没有得到任何回应。 .ajax 和 .getJASON 方法每次都会触发一个错误。
猜你喜欢
  • 2018-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多