0

我有以下来自网络方法的 json 输出。

{"d":"[{\"id\":1,\"username\":\"deepak_nhm\",\"companyid\":4,\"MaxEQuizScoreAvailable\":600,\"EQuizzesUserScoreTaken\":100,\"EQuizzesUserTaken\":1,\"firstname\":\"Deepak\",\"lastname\":\"Kerai\",\"avatarsmall\":\"/images_webdev/profile/634596544067649211654527189.jpeg\",\"company\":\"Orange\",\"CompanyRank\":1,\"OverAllRank\":3},{\"id\":2,\"username\":\"Mona_Co\",\"companyid\":1,\"MaxEQuizScoreAvailable\":600,\"EQuizzesUserScoreTaken\":100,\"EQuizzesUserTaken\":1,\"firstname\":\"Mona\",\"lastname\":\"Sadhu\",\"avatarsmall\":\"/images_webdev/profile/AspNetForumAvatarguy35.jpg\",\"company\":\"3 Retail\",\"CompanyRank\":1,\"OverAllRank\":3}]"}

如何呈现上述输出,因为以下尝试仅返回“未定义”)?

  <script type="text/javascript">
    $(document).ready(function () {
        GetProducts();
    });
    function GetProducts() {
        $.ajax({
            type: "POST",
            url: "Default.aspx/GetContestants",
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {

                // Replace the ul's content with the page method's return.
                var invoices = msg.hasOwnProperty("d") ? msg.d : msg;
                var invoicesInList = [];
                for (var i = 0; i < invoices.length; i++) {
                    invoicesInList.push("<li>" + invoices[i]["username"] + "</li>");
                    //console.log(msg.length);
                }
                $(invoicesInList.join("")).hide().appendTo("#ProductsList").fadeIn("slow");
            }
        });
    }
</script>

提前致谢。

4

1 回答 1

1

msg.d实际上是 json,所以你必须对其进行解码才能将其用作对象,例如

var invoices = msg.hasOwnProperty("d") ? JSON.parse(msg.d) : msg;
于 2013-08-05T18:59:49.840 回答