我在json中的输出来自web方法。
{"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}]"}
如何渲染上面的输出,因为下面的尝试只返回'undefined')?
<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>
提前致谢。
答案 0 :(得分:1)
msg.d
实际上是json,所以你必须解码才能将它用作对象,比如
var invoices = msg.hasOwnProperty("d") ? JSON.parse(msg.d) : msg;