由于某种原因,我无法获取JSON的值,有人可以帮助我吗?

function forex() {
    var to = document.getElementById("to").value;
    alert(to);
    var from = document.getElementById("from").value;
    alert(from);
    var amount = document.getElementById("amount").value;
    alert(amount);
    $.getJSON("http://rate-exchange.appspot.com/currency?from=" + from + "&to=" + to + "&q=" + amount, function (response) {
        alert(response);
    });

    }

最佳答案

Demo

由于Same Origin Policy,您的Javascript在其他域上执行,因此您无法通过Ajax访问rate-exchange.appspot.com上的资源。

在您的情况下,此特定站点支持JSONP,因此您可以使用jQuery的JSONP实现来绕过Same Origin Policy。 JSONP的工作方式是将目标URL作为<script>标记并使用回调,该回调不受Same Origin Policy约束。

如果$.getJSON()方法在URL中找到诸如callback=?之类的参数,它将使用JSONP。

例:

function forex() {
    var to = document.getElementById("to").value;
    var from = document.getElementById("from").value;
    var amount = document.getElementById("amount").value;

    $.getJSON("http://rate-exchange.appspot.com/currency?&callback=?", { from : from, to : to, q : amount }, function (response) {
        alert(response.v);
    });
}


我还将您的手动URL变量更改为首选对象,因为jQuery将处理URL编码。

07-24 19:07
查看更多