简体   繁体   English

在AJAX循环中创建div

[英]Creating divs in AJAX loop

I am getting data from the server side using AJAX, I am now trying to populate data from from a list of objects into divs, the problem I am having is that I can not create the div while inside of the foreach loop. 我正在使用AJAX从服务器端获取数据,现在我正尝试将对象列表中的数据填充到div中,我遇到的问题是在foreach循环中无法创建div。

    $(document).ready(function () {

        var divs = "";

        var url = "../Graphs/CreateChart";


        $.ajax({
            type: 'POST',
            url: url,
            success: function (data) {
                for (var i in data) {

                    var x = data[i];

                    for (var j in x) {
                        var val;
                        if (x.hasOwnProperty(j)) {

                            val = x[j].SpName;

                            if (x[j].SpName != "undefined") {
                                $('#a').appendTo('#content');
                                createBarChart("#a", "USP_Charts_BarChart1"); 
                            }
                        }
                    }
                }
            }, dataType: "json",
            cache: false
        });
    });
</script>

I am trying to populate where it says "#a" with val and also then I need to populate the div I write with the val for the id, but when I try to put the document.write inside of the loop, I get a blank screen, any ideas why it would do this? 我正在尝试用val填充显示“ #a”的地方,然后我也需要使用ID的val填充我写的div,但是当我尝试将document.write放入循环内时,我得到一个黑屏,为什么会有这个想法?

you're trying to append a created variable to your content? 您正在尝试将创建的变量附加到您的内容? Try making the markup a string FIRST then appending it. 尝试使标记成为字符串FIRST,然后附加它。

To test it try it without data. 要测试它,请尝试不使用数据。

$("<h2>HI</h2>").appendTo("#content");

If that works, then make a string that is the markup you want, with the data you need. 如果可行,则使用所需的数据创建一个字符串,作为所需的标记。

$("<a data='"+data.variable+"'></a>").appendTo("#content");

append and appendTo are VERY similar, but you need to use a string, not just an identifier, if the object doesn't exist yet. append和appendTo非常相似,但是如果对象尚不存在,则需要使用字符串,而不仅仅是标识符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM