如何从json api获取数据

时间:2015-04-30 13:15:34

标签: javascript jquery json

我正在尝试在html页面中获取json数据,所有数据都在获取,但只有一个数据不能获取原因?这是我的代码。

这是我的json数据,我必须获取" classified_id"但它显示未定义。

{
    "status": 200,
    "message": "classification Created successfully",
    "news_data": {
        "name": "abc",
        "description": "hello everyone",
        "email_id": "abc@gmail.com",
        "phone": "9097817522",
        "classified_id": 102
    }
}  

这是我的js文件,我在那里获取json数据。

success: function(data) {
    var arr = data.data;
    var htmlText = '';

    for ( var key in arr ) {
        htmlText += '<div onclick="delete('+ arr[key].classified_id +')" ></div>';
        htmlText += '<p class="user-name"> Name: ' + arr[key].name + '</p>';
        htmlText += '<p class="user-loc"> Description: ' + arr[key].description + '</p>';
        htmlText += '<p class="user-desc"> Email: ' + arr[key].email_id + '</p>';
        htmlText += '<p class="user-desc"> Phone: ' + arr[key].phone + '</p>'; 
    }

    $('.feed-activity-list').append(htmlText);
}

请帮我解决这个问题。 提前谢谢。

2 个答案:

答案 0 :(得分:1)

如果您单独识别密钥,则不需要循环:

var arr = data.news_data;
var htmlText = '';
htmlText += '<div onclick="delete(' + arr.classified_id + ')" ></div>';
htmlText += '<p class="user-name"> Name: ' + arr.name + '</p>';
htmlText += '<p class="user-loc"> Description: ' + arr.description + '</p>';
htmlText += '<p class="user-desc"> Email: ' + arr.email_id + '</p>';
htmlText += '<p class="user-desc"> Phone: ' + arr.phone + '</p>';

DEMO

答案 1 :(得分:1)

var data = {
    "status": 200,
    "message": "classification Created successfully",
    "news_data": {
        "name": "abc",
        "description": "hello everyone",
        "email_id": "abc@gmail.com",
        "phone": "9097817522",
        "classified_id": 102
    }
};
var arr = [];
    arr.push(data.news_data);
    var htmlText = '';

    for ( var key in arr ) {
        htmlText += '<div onclick="delete('+ arr[key].classified_id +')" > classified_id: ' + arr[key].classified_id + '</div>';
        htmlText += '<p class="user-name"> Name: ' + arr[key].name + '</p>';
        htmlText += '<p class="user-loc"> Description: ' + arr[key].description + '</p>';
        htmlText += '<p class="user-desc"> Email: ' + arr[key].email_id + '</p>';
        htmlText += '<p class="user-desc"> Phone: ' + arr[key].phone + '</p>'; 
    }

    $('.feed-activity-list').append(htmlText);

<强> Demo