雅虎 JSONP Ajax 请求包装在回调函数中

发布于 2024-11-18 13:49:13 字数 758 浏览 4 评论 0原文

我知道我可以使用 jquery、.ajax 和 jsonp 进行跨域 ajax 调用。我正在调用雅虎股票报价 API。一切正常,结果正在返回(我可以使用 Fiddler 看到。)问题是我收到一个 js 错误 YAHOO is undefined。我认为它有问题,因为 JSON 是在回调函数中格式化的,所以它的 json 语法不正确。我能做什么来修复它?谢谢!这是代码:

     $.ajax({
            type: 'GET',
            dataType: 'jsonp',
            jsonp: 'callback',
            jsonpCallback: 'YAHOO.Finance.SymbolSuggest.ssCallback',
            data:{
                query: request.term
            },
            url: 'http://autoc.finance.yahoo.com/autoc',
            success: function (data) {
                alert("yes");
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
            }
        });

I understand that I can make a crossdomain ajax call with jquery, .ajax, and jsonp. I am calling the yahoo stock quote api. Everything is working and the result is returning (I can see using Fiddler.) The problem is I get a js error YAHOO is undefined. I think its having problems because the JSON is formated within a callback function so its not correct json syntax. What can I do to fix it? Thanks! Here is the code:

     $.ajax({
            type: 'GET',
            dataType: 'jsonp',
            jsonp: 'callback',
            jsonpCallback: 'YAHOO.Finance.SymbolSuggest.ssCallback',
            data:{
                query: request.term
            },
            url: 'http://autoc.finance.yahoo.com/autoc',
            success: function (data) {
                alert("yes");
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
            }
        });

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

流年里的时光 2024-11-25 13:49:14

我想添加这个答案,因为上面的 user209245 的答案(来自 2011 年)似乎不再有效。我是这样做的:

  1. 使用 YQL Console 为您想要获取的股票构建查询,例如 Apple:

    <块引用>

    从 yahoo.finance.quotes 中选择*,其中符号=“AAPL”

  2. 确保选择 JSON 并指定 JSONP 回调,例如 quote
  3. 单击“测试”
  4. 插入它为您生成的 REST 查询这个:

    var 引用;
    
    $(文档).ready(函数() {
        $.ajax({
            网址: “http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%3D%22AAPL%22&format=json&diagnostics=true& env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=quote",
            数据类型:“jsonp”,
            jsonp: "回调",
            jsonpCallback: "引用"
        });
    
        报价=函数(数据){
            $(".price").text("$" + data.query.results.quote.AskRealtime);
        };
    });
    

    然后在您的页面上将显示 .price

    <预><代码>$543.21

Of当然,一旦你得到数据,你就可以显示任何你想要的东西;我只是用价格作为例子,因为这就是我需要的。

I wanted to add this answer since it looks like user209245's answer above (which is from 2011) no longer works. Here's how I did it:

  1. Use the YQL Console to build a query for the stock you want to get, e.g. Apple:

    select * from yahoo.finance.quotes where symbol="AAPL"

  2. Make sure JSON is selected and specify a JSONP callback, e.g. quote
  3. Click Test
  4. Plug in the REST query that it generates for you like this:

    var quote;
    
    $(document).ready(function() {
        $.ajax({
            url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%3D%22AAPL%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=quote",
            dataType: "jsonp",
            jsonp: "callback",
            jsonpCallback: "quote"
        });
    
        quote = function(data) {
            $(".price").text("$" + data.query.results.quote.AskRealtime);
        };
    });
    

    Then on your page the .price <div> would display:

    $543.21
    

Of course, once you get the data back you can display anything you want; I'm just using price as an example since that's what I needed this for.

缱倦旧时光 2024-11-25 13:49:14

以下是我如何让它工作:

我使用 .ajax 而不是 .jsonp,因为您需要提供 url 参数。
您还需要在代码中定义 Yahoo 回调函数的名称。
这是一个解释如何使用 Yahoo 回调函数及其 Web 服务的链接。

http://developer.yahoo.com/javascript/json.html#callbackparam

这是代码:

<script type="text/javascript">
    // this variable must be defined this way
    var YAHOO = {
        Finance: {
            SymbolSuggest: {}
        }
    };

    $(document).ready(function(){           
        var query;

        query = 'Yahoo';        
        if (query.length > 0)
        {

          $.ajax({
              type: "GET",
              url: "http://d.yimg.com/autoc.finance.yahoo.com/autoc",
              data: {query: query},
              dataType: "jsonp",
              jsonp : "callback",
              jsonpCallback: "YAHOO.Finance.SymbolSuggest.ssCallback",
          });
          // call back function
          YAHOO.Finance.SymbolSuggest.ssCallback = function (data) {
            alert(JSON.stringify(data));
          }
        }

    }); 


    </script>   

Here is how I got it to work:

I used .ajax instead of .jsonp because you need to give the url parameters.
You also need to define in your code the name of the Yahoo callback function.
Here is a link explaining how to use Yahoo callback function with its web services.

http://developer.yahoo.com/javascript/json.html#callbackparam

Here is the code:

<script type="text/javascript">
    // this variable must be defined this way
    var YAHOO = {
        Finance: {
            SymbolSuggest: {}
        }
    };

    $(document).ready(function(){           
        var query;

        query = 'Yahoo';        
        if (query.length > 0)
        {

          $.ajax({
              type: "GET",
              url: "http://d.yimg.com/autoc.finance.yahoo.com/autoc",
              data: {query: query},
              dataType: "jsonp",
              jsonp : "callback",
              jsonpCallback: "YAHOO.Finance.SymbolSuggest.ssCallback",
          });
          // call back function
          YAHOO.Finance.SymbolSuggest.ssCallback = function (data) {
            alert(JSON.stringify(data));
          }
        }

    }); 


    </script>   
泛滥成性 2024-11-25 13:49:14

这是工作示例:参见回调=?在我的查询结束时使其工作。
该示例可以作为独立的 html 复制过去。

https://github.com/cirs/PortfolioApp/blob/master /PortfolioApp-Step1-GetData.html

Here is the working example : See the callback=? at the end of my query to make it work.
This example can be copied past as a standalone html .

https://github.com/cirs/PortfolioApp/blob/master/PortfolioApp-Step1-GetData.html

℡Ms空城旧梦 2024-11-25 13:49:14

这是对我有用的修改版本:

$(document).ready(function() {
    $.ajax({
        url: "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22AAPL%22)%0A%09%09&format=json&diagnostics=true&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback=quote",
        dataType: "jsonp"
    });

    window.quote = function(data) {
        console.log(data);
    };
});

Here's an amended version that worked for me:

$(document).ready(function() {
    $.ajax({
        url: "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22AAPL%22)%0A%09%09&format=json&diagnostics=true&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback=quote",
        dataType: "jsonp"
    });

    window.quote = function(data) {
        console.log(data);
    };
});
梦里泪两行 2024-11-25 13:49:14

这是一个 js 小提琴:
https://jsfiddle.net/vham369w/1/

使用 $.getJson 而不是 $.ajax

JS

$(document).ready(function() {
    var symbol = 'AAPL'
    var url =  "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%3D%22"+symbol+"%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
    $.getJSON(url + "&callback=?", null, function(data) {
        console.log(data);
        $("#realtime").text("$" + data.query.results.quote.AskRealtime);
        $("#ask").text("$" + data.query.results.quote.Ask);
    });
});

HTML

Ask:
<div id="ask">
    loading ask
</div>
Realtime (null if market is closed):
<div id="realtime">
    loading realtime
</div>

Here is a js fiddle for this:
https://jsfiddle.net/vham369w/1/

using $.getJson instead of $.ajax

JS

$(document).ready(function() {
    var symbol = 'AAPL'
    var url =  "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%3D%22"+symbol+"%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
    $.getJSON(url + "&callback=?", null, function(data) {
        console.log(data);
        $("#realtime").text("$" + data.query.results.quote.AskRealtime);
        $("#ask").text("$" + data.query.results.quote.Ask);
    });
});

HTML

Ask:
<div id="ask">
    loading ask
</div>
Realtime (null if market is closed):
<div id="realtime">
    loading realtime
</div>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文