1

通貨換算に関するこのSO 投稿を見つけました。
私は JSON を初めて使用するので、この URL から変数に結果を送信して取得する方法を質問します。

http://www.google.com/ig/calculator?hl=en&q=100GBP=?EUR 
   //this url above gives back this line under
{lhs: "100 British pounds",rhs: "115.538154 Euros",error: "",icc: true} //answer html

URLはブラウザ上で動作するので、ajax呼び出しで送信しようとしましたが、このエラーが発生しました。

405 (Method Not Allowed) 
Origin http://www.mysite.com is not allowed by Access-Control-Allow-Origin.

私のアヤックス:

var req = new Request({
    method: 'post', 
    url: 'http://www.google.com/ig/calculator?hl=en&q=100GBP=?EUR',
    onSuccess: function(response) {
        console.log(response);
    }
}).send();

私は mootools を使用しているので、jQuery は使用しないでください。

4

2 に答える 2

3

ここでの Google API は有効な JSONP を返さず (応答キーに " がない)、CORS が好きではありません。「独自のプロキシをコーディングする」か、他の誰かのプロキシを使用するかのいずれかになります。

{lhs: "100 British pounds",rhs: "115.538154 Euros",error: "",icc: true} 

正しい応答は次のようになります。

{"lhs": "100 British pounds", "rhs": "115.538154 Euros", "error": "","icc": true} 

この代替案はうまくいきます:

Request.exchange = new Class({

    Extends: Request.JSONP,

    options: {
        url: 'http://rate-exchange.appspot.com/currency?from={from}&to={to}&q={amount}',
        amount: 1
    },

    initialize: function(options){
        this.setOptions(options);
        this.options.url = this.options.url.substitute(this.options);
        this.parent();
    }

});

new Request.exchange({
    from: 'GBP',
    to: 'JPY',
    amount: '100',
    onSuccess: function(response) {
        console.log(response, response.rate, response.v);
    }
}).send();

MooTools-more の Request.JSONP をサブクラス化して from/to/amount を追加し、http://rate-exchange.appspot.com api を google に使用て、json を修正します (同じデータ)。

上記の jsfiddle での動作 (コンソールを見てください): http://jsfiddle.net/bBHsW/

http://finance.yahoo.com/を使用して csv などを取得することもできます。

于 2013-07-15T15:07:09.177 に答える
0

Google API と通信するバックエンドを作成する必要があります。次に、バックエンドに対して ajax リクエストを実行できます。

Google API で直接 ajax リクエストを行うことはできません。

参照: https://developer.mozilla.org/en/docs/HTTP/Access_control_CORS

于 2013-07-15T14:57:17.637 に答える