Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
668 views
in Technique[技术] by (71.8m points)

jquery - Yahoo JSONP Ajax Request Wrapped in callback function

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);
            }
        });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...