如何将每个json数组项放入它自己的div中

时间:2013-11-11 20:56:12

标签: jquery ajax json

HTML:

<div class="myThing"></div>
<div class="myThing2"></div>

jquery的:

$(document).ready(function() {
     $.getJSON('/test/getsubtopics.php', function(data) {
        $(".myThing").html(data.subtopic_id);
        $(".myThing2").html(data.subtopic_name);
     });   
});

我希望每个subtopic_id和subtopic_name都有自己的.myThing和.myThing2 divs(分别)

这是我的数据来自getsubtopics.php:

$subtopic_id = array();
$subtopic_name = array();

$find_forum_subtopics = mysqli_query($con, "SELECT id, subTopicName FROM forumSubTopics WHERE topicID='$forum_topic_id' ORDER BY listValue ASC");

    while ($find_forum_subtopics_row = mysqli_fetch_array($find_forum_subtopics)) {
        $subtopic_id[] = $find_forum_subtopics_row['id'];
        $subtopic_name[] = $find_forum_subtopics_row['subTopicName'];
    }

$arr = array("subtopic_id" => $subtopic_id, "subtopic_name" => $subtopic_name);
echo json_encode($arr);

根据控制台日志,这里有什么回来:

subtopic_id: Array[56]
0: "1"
1: "2"
2: "3"
3: "4"
4: "5"
5: "6"
6: "7"
7: "8"
8: "9"
9: "10"
10: "12"
11: "13"
12: "14"
13: "15"
14: "16"
15: "17"
16: "18"
17: "19"
18: "20"
19: "21"
20: "22"
21: "23"
22: "24"
23: "25"
24: "26"
25: "27"
26: "28"
27: "29"
28: "30"
29: "31"
30: "32"
31: "33"
32: "34"
33: "35"
34: "36"
35: "37"
36: "38"
37: "39"
38: "40"
39: "41"
40: "42"
41: "43"
42: "44"
43: "45"
44: "46"
45: "47"
46: "48"
47: "49"
48: "50"
49: "51"
50: "52"
51: "53"
52: "54"
53: "55"
54: "56"
55: "57"

subtopic_name: Array[56]
0: "So Glad To Have You!"
1: "What's New in the World of Marriage?"
2: "Feedback and Site Help"
3: "Companionship"
4: "Commitment"
5: "Communication"
6: "Selflesness"
7: "Respect"
8: "Forgiveness"
9: "Trust"
10: "Intimacy and Quality Time"
11: "Mood and Romance"
12: "Foreplay and Sex"
13: "Physical Appearance and Attraction"
14: "His Needs and Her Needs"
15: "Date Nights and Fun Ideas"
16: "Wife/Mother"
17: "Husband/Father"
18: "Pregnancy"
19: "Parenting"
20: "Children"
21: "In-Laws"
22: "Grandparenting"
23: "Blended Family"
24: "Military Marriages"
25: "Interracial/Intercultural/Interfaith Marriages"
26: "Long Distance Marriages"
27: "Aging Parents"
28: "Adoption"
29: "Friends/Ex's"
30: "Communication"
31: "Credit/Debt"
32: "Budgeting/Planning"
33: "Giving/Saving"
34: "Investing"
35: "Child SUpport/Alimony"
36: "Unemployment"
37: "Just Married"
38: "Depression"
39: "Stress"
40: "Illness/Disability"
41: "Infertility"
42: "Abortion"
43: "LGBT"
44: "Pornography"
45: "Abuse and Addiction"
46: "Separation"
47: "Divorce"
48: "Affairs/Adultery"
49: "Remarriage"
50: "Faith and Spirituality"
51: "Temptation"
52: "Lack of Intercourse"
53: "Drifting Aapart"
54: "Empty Nest"
55: "Losing a Loved One"

3 个答案:

答案 0 :(得分:0)

$.getJSON('/test/getsubtopics.php', function(data) {
    $.each(data, function (inData) {
        $.each(inData, function () {
            $("body").append('<div class="myThing">' + inData.subtopic_id + '</div>'); 
            $("body").append('<div class="myThing2">' + inData.subtopic_name + '</div>');  
        });             
    });
});

您需要使用jQuery data函数遍历$.each对象。然后,只需在每次迭代时附加一个包含相应内容的新<div>

答案 1 :(得分:0)

你必须在响应中分离回来的数组。索引应该对应于数组的php(.subtopic_id.subtopic_name)。然后只需按如下方式更改代码:

$(document).ready(function () {
    $.getJSON('/test/getsubtopics.php', function (data) {
        for (var i = 0; i < data.subtopic_id.length; i++) {//i is current index for subtopic_id and subtopic_name
            $("body").append('<div class="myThing">' + data.subtopic_id[i] + '</div>')//get id by index
                .append('<div class="myThing2">' + data.subtopic_name[i] + '</div>'); //get name by index
        }
    });
});

另外需要注意的是,编写这样的循环会更加高效,以最大限度地减少附加到document.body的数量。

var html = "";//holds the html so far
for (var i = 0; i < data.subtopic_id.length; i++) {
    html += '<div class="myThing">' + data.subtopic_id[i] + '</div>';
    html += '<div class="myThing2">' + data.subtopic_name[i] + '</div>'; //get name by index
}
$("body").append(html);//append all the html at once

答案 2 :(得分:0)

看看这个有效的例子:

&#13;
&#13;
//native JS for get the JSON
var getJSON = function(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'json';
    xhr.onload = function() {
      var status = xhr.status;
      if (status == 200) {
        callback(null, xhr.response);
      } else {
        callback(status);
      }
    };
    xhr.send();
};

//you change this part for your json
getJSON('https://jsonplaceholder.typicode.com/photos', function (err, data){createDivs(err, data);});

function createDivs(err, data) {
    for (i = 0; i < data.length; i++) {
    $("#items").append('<div id="'+ data[i].id +'" class="itemClass">"'+ 	data[i].title +'"</div> <div class="rectangle" style="background-image: 	url('+data[i].url+');"></div><br>');
    
    //just break after 10
    if(i == 10){
    break;
    }
    }
    
    }
&#13;
.itemClass{
    width:200px;
    height:40px;
    background:grey;
    color:white;
}

.rectangle{
    width:200px;
    height:100px;

}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="items"></div>
&#13;
&#13;
&#13;