weixin_33743703 2014-08-02 11:45 采纳率: 0%
浏览 368

通过ajax获取json数据

The question I am asking is a basic question because I am new in json and ajax.

so I have a json data of name , task , date and status I am getting data through ajax but it is not showing in on my page.

responce

my ajax code is this:

$(document).ready(function(e) {     
    // Using the core $.ajax() method
    $.ajax({
        url: "getdata.php",
        type: "GET",
        dataType : "json",
        success: function( json ) {
            $( "<h1/>" ).text( json.name ).appendTo( "body" );
            $( "<div class=\"content\"/>").html( json.task ).appendTo( "body" );
        },
        complete: function( xhr, status ) {
            alert( "The request is complete!" );
        }
    }); 
});

this is my json data:

[
  {"name":"Usman ","task":"Getting work","date":"27-07-2014 12:28:45 PM","status":"1"},
  {"name":"Hamza","task":"Starting work","date":"27-07-2014 12:29:36 PM","status":"1"},
  {"name":"Hamza","task":"Geted","date":"27-07-2014 2:04:07 PM","status":"1"},
  {"name":"Hamza","task":"Start work","date":"02-08-2014 3:56:37 PM","status":"1"}
]

I don't know why It is not appending html data but it is showing complete alert.

I have added fiddle even if it is not working.

Fiddle

  • 写回答

2条回答 默认 最新

  • weixin_33736048 2014-08-02 11:49
    关注

    Ok, i see you actually getting results so i guess you do have a success. You do have a flaw though. You are trying to access properties directly, but your json is an array of objects and not an object.

    You need to do a foreach itteration.

    json.forEach(function (entry) {
        $( "<h1/>" ).text( entry.name ).appendTo( "body" );
        $( "<div class=\"content\"/>").html( entry.task ).appendTo( "body" );
    });
    
    评论

报告相同问题?