使用jQuery AJAX加载JSON数据
我需要在单击按钮时打印此信息并按日期排序,到目前为止我有这个:我有json文件看起来像这样,但我无法在页面上打印它仍然没有得到按日期排序部分。 我不确定问题是否是我正在使用的ajax版本的链接或问题是什么,因为我在youtube上看到了一个看起来像这样的例子,它工作得很好。
JSON:
[ { "users": [ { "name": "user1", "Endorsement": "some comment", "date": "8/11/2012" }, { "name": "user2", "Endorsement": "some comment2", "date": "9/27/11" }, { "name": "user3", "Endorsement": "some comment3" }, { "name": "user4", "Endorsement": "some comment4", "date": "4/2/13" }, { "name": "user5", "Endorsement": "some comment5" }, { "name": "user6", "Endorsement": "some comment6", "date": "3/17/13" }, { "name": "user7", "Endorsement": "some comment7", "date": "5/22/13" }, { "name": "user8", "Endorsement": "some comment8", "date": "9/27/13" } ] }
]
HTML已更新:
Contact $(document).ready(function () { $('.dropdown-toggle').dropdown(); });
JS更新:
$(“#clickme”)。click(function(){
$.getJSON("users.json", function (data) { var items = []; $.each(data, function (key, dvalue) { $.each(dvalue, function (key, value) { items.push('' + value + ' '); }); }); $('
', { 'class': 'interest-list', html: items.join('') }).appendTo('body'); }); });
但是没有用。 意思是不加载用户名; 相反,每次点击链接时都会打印出这样的内容:
•[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
jason缺少一些逗号,json中的每一行都应以逗号结尾,除非它是范围中的最后一个子节点,这使得:
[ { "users": [ { "name": "user1", "Endorsement": "some comment", "date": "8/11/2012" }, { "name": "user2", "Endorsement": "some comment2", "date": "9/27/11" }, { "name": "user3", "Endorsement": "some comment3" }, { "name": "user4", "Endorsement": "some comment4", "date": "4/2/13" }, { "name": "user5", "Endorsement": "some comment5" }, { "name": "user6", "Endorsement": "some comment6", "date": "3/17/13" }, { "name": "user7", "Endorsement": "some comment7", "date": "5/22/13" }, { "name": "user8", "Endorsement": "some comment8", "date": "9/27/3" } ] } ]
试试吧!
$("button").click(function () { $.getJSON("users.json", function (obj) { $.each(obj.users, function (key, value) { $("ul").append("" + value.name + " "); }); });
});
如果有错误,请在浏览器中使用调试控制台。 要么做一个小提琴,要么写出什么是错误。 并且你的html中似乎没有ul元素。
json无效。 我使用http://jsonlint.com/进行了validation,并在第6行显示错误。您在下面的部分留下了逗号:
"Endorsement": "some comment" "date":"8/11/2012"
这是第一个认可日期对
$("button").click(function () { $.getJSON("users.json", function (data) { for (i in data) { for (k in data[i]) { alert(data[i][k]); } }); });
$.ajax({ type:'POST', url:'Default.aspx/GetPro', data:"{Pid:'"+ faram+"'}", contentType: 'application/json; charset=utf-8', dataType: 'json', async: true, cache: false, success: function(msg) { alert("{Pid:'"+ faram+"'}"); var orders =msg; if (orders.length > 0) { test(orders); } else { alert("No Record Found"); } }, error: function(xhr, textStatus, errorThrown) { alert(xhr.status); alert(errorThrown); alert(xhr.responseText); }
});
function test(data) { for (i in data) { //ProductName Is Property Field Of c# Object alert(data[i]['ProductName']) } }