通过JavaScript对象循环后动态创建文本框文本框、对象、动态、JavaScript

2023-09-10 21:59:33 作者:最是奢侈少年梦

我发送一些信息,通过一个AJAX请求到服务器并接收一些数据问题和它们的ID的一个JSON数组。一个JavaScript

I have a javascript that sends some info to through an ajax request to the server and receives some data as Questions and their's ID's as a json array.

这是什么反应JSON数组我从服务器接收的样子:

This is what the response json array i receive from the server looks like:

   [
     {
      "ID":"1",
      "question":"Write a function called addNum. "
        },
     {
      "ID":"3",
      "question":"Write a function called sumDouble "
      }
    ]

这是JavaScript的:

And this is javascript:

$(document).ready(function(){
    $("form#input_qnumber").submit(function() {

    var questions = $('#questions').attr('value'); // written question
    var quizname = $('#quizname').attr('value');

    if (questions) { // values are not empty
        $.ajax({
            type: "POST",
            url: "https://xxxx",
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            dataType: "application/json",
            data: 'questions='+questions+'&quizname='+quizname,

            success: function (data) 
            {
                var JSONObject = JSON.parse(data); 

                for (var key in JSONObject) {
                    if (JSONObject.hasOwnProperty(key)) {
                        console.log(JSONObject[key]["ID"] + ", " + JSONObject[key]["question"]);
                    }
                }



            }

        });
    }
    else {
        $('div#createquizresp').text("Enter question ID's separated by a comma to be included in the quiz");
        $('div#createquizresp').addClass("error");
    } // else
    $('div#createquizresp').fadeIn();
    return false;
});
});

正如你看到的,我可以通过它解析响应JSON转换为JavaScript对象数组,循环和转储的内容控制台。我想,虽然是创建textarea元素,给予其ID从我的阵列属性的ID键并用该数组中的相应问题的关键贴上标签。在此之后我可以追加元素,我的HTML里面一个div。但我真的不知道怎么做,或者如果它甚至有可能。请HALP。

As you see, I can parse the response json into a javascript object array, loop through it and dump the contents in console. What I would like though would be to create textarea element, give its id attribute the 'ID' key from my array and label it with the corresponding question key from the array. After this I can just append the element to a div inside my html. But I am not really sure how to do it or if its even possible. Please HALP.

推荐答案

如果你想还一个标签元素;

if you want also a label element;

for (var key in JSONObject) {
    if (JSONObject.hasOwnProperty(key)) {
        $('<label>')
            .attr('for', JSONObject[key]["ID"])
            .html(JSONObject[key]["question"])
            .appendTo('wherever_you_want');
        $('<textarea>')
            .attr('id', JSONObject[key]["ID"])
            .appendTo('wherever_you_want');
    }
}