1

なんらかの理由で 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);
    });

    }
4

2 に答える 2

1

デモ

Same Origin Policyにより、JavaScript が別のドメインで実行されているため、ajax 経由で rate-exchange.appspot.com のリソースにアクセスできません。

あなたの場合、この特定のサイトはJSONPをサポートしているため、jQuery の JSONP 実装を使用して同一生成元ポリシーを回避できます。JSONP は、ターゲット URL を<script>タグとして含め、コールバックを使用することで機能します。これは、Same Origin Policy によってバインドされていません。

この$.getJSON()メソッドは、URL にcallback=?.

例:

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);
    });
}

また、jQuery が URL エンコーディングを処理するため、手動の URL 変数を好ましいオブジェクトに変更しました。

于 2013-10-17T11:14:17.577 に答える
0

以下のコードの代わりに:

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

次のコードを使用します。

$.ajax({
  url: "http://rate-exchange.appspot.com/currency?from=" + from + "&to=" + to + "&q=" + amount,
  dataType: 'jsonp',
  success: function(response) {
        alert(response.v);
  }
});
于 2013-10-17T11:23:59.090 に答える