在ASP.NET中使用YQL和JQuery获取股票信息

时间:2014-03-13 15:26:45

标签: javascript jquery asp.net json yql

我正在尝试使用我的ASP.NET项目中的YQL查询来检索股票信息。我正在使用jquery来调用json来检索数据。问题是,当我单击页面上的“GetData”按钮时,它只刷新页面并且不显示任何数据。如果我在visual studio中以调试模式运行项目,它将返回库存信息并显示在页面上,但是在调试结束时它会清除页面。这是代码:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script src="Scripts/jquery-1.11.0.min.js" type="text/javascript"></script>

        <script type="text/javascript">
            function getData() {
                var url = "http://query.yahooapis.com/v1/public/yql";
                var data = encodeURIComponent("select * from yahoo.finance.quotes where symbol in ('MSFT')");
                $.getJSON(url, 'q=' + data + "&format=json&diagnostics=true&env=http://datatables.org/alltables.env")
            .done(function (data) {
                $("#result").text("Bid Price: " + data.query.results.quote.LastTradePriceOnly);
                alert(data.query.results.quote.LastTradePriceOnly);
            })
            .fail(function (jqxhr, textStatus, error) {
                var err = textStatus + ", " + error;
                $("#result").text('Request failed: ' + err);
            });
            }

        </script>
    </head>
    <body>

        <form id="form1" runat="server">    
            <div id='result'>No Price</div>
            <button type="submit" onClick="getData();">Get Data</button>         
        </form>
    </body>
    </html>

JsFiddle:http://jsfiddle.net/a3tuP/

有人知道为什么即使在JSON调用中返回数据也会清除数据吗?

感谢。

1 个答案:

答案 0 :(得分:1)

表单由按钮上的提交操作提交 尝试重新考虑这样的事情并添加.preventDefault()

<强> HTML

 <form id="form1" runat="server">    
        <input type="text" id="symbol" />
        <div id='result'>No Price</div>
        <button type="submit">Get Data</button>
    </form>

<强> JS

function getData(e) {
    //prevent sumbitting the form 
    e.preventDefault()
    var url = "http://query.yahooapis.com/v1/public/yql";
    var symbol = $("#symbol").val();
    var data = encodeURIComponent("select * from yahoo.finance.quotes where symbol in ('BGG')");

    $.getJSON(url, 'q=' + data + "&format=json&diagnostics=true&env=http://datatables.org/alltables.env")
        .done(function (data) {
        $("#result").text("Bid Price: " + data.query.results.quote.LastTradePriceOnly);
    })
        .fail(function (jqxhr, textStatus, error) {
        var err = textStatus + ", " + error;
            $("#result").text('Request failed: ' + err);
    });
}

//bind the submit event
$(document).on("submit", "#form1" getData)
相关问题