简体   繁体   中英

Having trouble with Jquery/JSON

I'm trying to iterate through a JSON response that's generated from my code-behind. The string that my code is returning is:

[{"Symbol":"^GDAXI","Last":"6787.49","Change":"+38.73"},{"Symbol":"^FTSE","Last":"5894.65","Change":"+18.72"}]

I'm trying to iterate through this using:

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script type="text/javascript" src="/Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
    $(document).ready(function (){
        $.ajax({
            type: "POST",
            url: "Stocks.asmx/GetQuote",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (stocks) {
                $(stocks).each(function (index) {
                    $('#stocks').append("<li>" + this.Symbol + "</li>");
                });                    
            }
        });
    });
</script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<p>
    <ul id="stocks"></ul>
</p>
</asp:Content>

All I'm getting is an li item with 'undefined'.

Where am I going wrong?

That .each() doesn't look right.

Try:

$(stocks).each(function (index, value) {
    $('#stocks').append("<li>" + value.Symbol + "</li>");
}); 

The callback passed to 'each' receives two arguments. You got to write something like this:

$(stocks).each(function(index, data){ console.log(data.Symbol); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM