Ajax怎么获取Json数据
$("a").click(function(){$.ajax({type:"get",url:"test1.json",dataType:"json",success:f...
$("a").click(function(){
$.ajax({
type:"get",
url:"test1.json",
dataType:"json",
success:function(response,status,xhr){
$.each(response,function(index,value){
$firstName = response[index].firstName;
$lastName = response[index].lastName;
$("ul").append("<li>"+index+"----firstName:"+$firstName+"///lastName:"+$lastName+"</li>");
});
}
});
});
json:
{
"programmers": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" }
],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
{ "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
{ "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
]
} 展开
$.ajax({
type:"get",
url:"test1.json",
dataType:"json",
success:function(response,status,xhr){
$.each(response,function(index,value){
$firstName = response[index].firstName;
$lastName = response[index].lastName;
$("ul").append("<li>"+index+"----firstName:"+$firstName+"///lastName:"+$lastName+"</li>");
});
}
});
});
json:
{
"programmers": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" }
],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
{ "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
{ "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
]
} 展开
1个回答
展开全部
$("a").click(function() {
$.ajax({
type: "get",
url: "test1.json",
dataType: "json",
success: function(response, status, xhr) {
for (var p in response) {
var li = $("<li>" + p + "</li>"),
arr = response[p];
var ul = $("<ul>");
li.append(ul);
for (var i = 0; i < arr.length; i++) {
var lii = $("<li>");
var obj = arr[i];
for (var k in obj) {
lii.append("<div>" + k + ": " + obj[k] + "</div>");
}
ul.append(lii);
}
$("ul").append(li);
}
});
});
});
追问
为什么我在网上查看会用到eval()这个的,这个是什么时候用到
追答
你的response是字符串类型还是对象,如果是字符串的json,那就eval转为object就可以了
如果是object,就不需要了
var str = "{}";
var obj = eval("("+str+")");
好了,更多的细节不多说了,多查查网就知道了,采纳即可
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询