javascript - jQuery + JSONP + 雅虎查询语言

标签 javascript jquery json web-services jsonp

我想从外部来源获取实时汇率,所以我找到了这个很棒的网络服务:

Currency Convertor

这项服务工作得很好,唯一的缺点是它不提供 JSONP 结果,只提供 XML。因此,我们在尝试使用 jQuery $.ajax() 使用此 Web 服务时遇到了跨浏览器问题。

所以我找到了Yahoo Query Language它以 JSONP 和 mangae 的形式返回结果以使用其他 Web 服务并将结果返回给我。这也有效,这是一个示例 URL:

http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%3D'http%3A%2F%2Fwww.webservicex.net%2FCurrencyConvertor.asmx%2FConversionRate%3FFromCurrency%3DNOK%26ToCurrency%3DEUR'&format=json&diagnostics=true&callback=cbfunc

这个 URL 返回 JSONP 结果并且工作得很好,但是当我在我的代码中使用它时出现问题:

$.ajax({
  type: "GET",
  url: urlToWebservice,
  contentType: "application/json; charset=utf-8",
  dataType: "jsonp",
  success: function(data) {
    $("#status").html("OK: " + data.text);
  },
  error: function(xhr, textStatus, errorThrown) {
    $("#status").html("Unavailable: " + textStatus);
  }
});

当我尝试运行此代码时,没有任何反应,而且我可以在我的 Firebug javascript 调试器中看到此错误消息:

cbfunc is not defined

cbfunc 是围绕 JSON 响应的容器的名称,但为什么它说未定义?

编辑:

这是我的新代码,但我仍然得到 cbfunc is not defined

$.ajax({
  url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%3D'http%3A%2F%2Fwww.webservicex.net%2FCurrencyConvertor.asmx%2FConversionRate%3FFromCurrency%3DNOK%26ToCurrency%3DEUR'&format=json&callback=cbfunc",
  dataType: 'jsonp',
  jsonp: 'callback',
  jsonpCallback: 'cbfunc'
});

function cbfunc(data) {
  alert("OK");
}

并且永远不会触发“OK”消息...

最佳答案

如果可用,在对 $.ajax 的调用中使用 jsonpCallback 参数,例如:

 jsonpCallback: "cbfunc",

它的描述,从 jQuery API docs 读取:

Specify the callback function name for a jsonp request. This value will be used instead of the random name automatically generated by jQuery.

文档稍后继续说:

It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests.

但是,在使用 YQL 时,建议使用这种“首选”行为。正是这种方法不理想的原因可能会使这个答案过于冗长,所以这里有一个链接(来自 YQL 博客)详细说明了 jQuery 首选方法的问题,使用 jsonpCallback 等等:Avoiding rate limits and getting banned in YQL and Pipes: Caching is your friend

关于javascript - jQuery + JSONP + 雅虎查询语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3113924/

相关文章:

javascript - 如何将文本输入光标的初始位置设置为左上角

javascript - AngularJS 与 UI Router 的奇怪查询行为

jquery - 带有 CORS 的 IE9 jQuery AJAX 返回 "Access is denied"

jquery - 这个 jQuery 函数的正确选择器是什么?或 $ ("#myElement")[0].href 与 $ ("#myElement").href

json - 如何将 JSON 解析为 UITableview

jquery - 如何使用json获取youtube中的视频图像URL

javascript - AppendChild 在 `for` 循环或 `forEach `

javascript - 分析 `if(x)` VS `if(x===undefined)`

javascript - Bootstrap datepicker 显示没有错误但无法正常工作

java - 将不同 JSON 键的值设置为 Field Play 框架