从Google计算器api的JSON字符串中获取值
Get value from JSON string from Google calculator api
我发现这篇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.
我的ajax:
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。
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以从/添加到/数量并使用http://rate-exchange.appspot.comapi到google,后者修复了他们的json(相同的数据)。
上面在jsfiddle上的操作(查看控制台):http://jsfiddle.net/bBHsW/
您也可以使用http://finance.yahoo.com/并获取csv等。
您必须制作一个与Google API对话的后端。然后您可以对后端进行ajax请求。
您不能在Google API上直接执行ajax请求。
请参阅:https://developer.mozilla.org/en/docs/HTTP/Access_control_CORS
相关文章:
- 通过字符串获取JSON对象
- 将敲除绑定应用于模板,并将结果作为字符串获取
- 使用字符串获取本地对象的属性
- 如何使用 jQuery 在标签的 for 属性中使用子字符串获取标签元素的值
- 使用 Javascript 将 Java 渲染为字符串获取最终 HTML
- 如何使用正则表达式从此字符串获取电子邮件
- 维基媒体API从JSON字符串获取相关数据
- 如何使用jQuery将HTML数据值作为字符串获取
- 带有换行符的JSP+HTML-将其作为字符串获取,并删除"新线”;
- 如何从字符串获取url-jQuery或Javascript
- QML-将JS函数的代码作为字符串获取
- cookie字符串获取并设置jquery控件的属性
- 通过字符串获取HTML元素
- 从绝对url字符串获取锚值
- 在myObj.one.two.three.field中,当字段有2个或更多嵌套级别时,通过路径字符串获取对象字段
- 从带有moment的非本地ISO8601字符串获取时间(小时,分钟)
- 使用javascript使用parseFloat和parseInt无法正常工作的字符串获取价格
- 如何从json字符串获取键值
- 使用javascript从给定字符串获取电子邮件id
- 从Json字符串获取数据到javascript (jQuery)