Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/432.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用ajax和json动态添加元素会破坏页面布局_Javascript_Json_Ajax - Fatal编程技术网

Javascript 使用ajax和json动态添加元素会破坏页面布局

Javascript 使用ajax和json动态添加元素会破坏页面布局,javascript,json,ajax,Javascript,Json,Ajax,我有一个用jquery mobile构建的页面。如果我用静态代码填充列表: <script> document.write('<ul data-role="listview">'); document.write('<li data-icon="false"><a href="#" id="mortadella"><img src="images/app/prod.jpg"><h2>Sisa</h2>

我有一个用jquery mobile构建的页面。如果我用静态代码填充列表:

    <script>
document.write('<ul data-role="listview">');


document.write('<li data-icon="false"><a href="#" id="mortadella"><img src="images/app/prod.jpg"><h2>Sisa</h2><p class="wrap">mortadella affettatagr.120</p><span class="ui-li-count">2,70 €</span></a></li>');
document.write('<li data-icon="false"><a href="#" id="mortadella"><img src="images/app/prod.jpg"><h2>Sisa</h2><p class="wrap">mortadella affettatagr.120</p><span class="ui-li-count">2,70 €</span></a></li>');             



document.write('</ul>');

</script>

document.write(“
    ”); document.write(“
  • ”); document.write(“
  • ”); 文件。写(“
”);
我得到这个结果:

现在,我试着以友好的方式来做,用ajax和json从数据库中读取数据。 代码如下:

<script>
document.write('<ul data-role="listview">');
    $.ajax({
        url: 'db_to_app_prod.php',
        dataType: 'jsonp',
        jsonp: 'jsoncallback',
        timeout: 5000,
        success: function(data, status){
            $.each(data, function(i,item){ 

document.write('<li data-icon="false"><a href="#" id="mortadella"><img src="images/app/prod.jpg"><h2>Sisa</h2><p class="wrap">mortadella affettatagr.120</p><span class="ui-li-count">2,70 €</span></a></li>');

            }); 

        },
        error: function(){
           output.text('There was an error loading the data.');
        }
    });


document.write('</ul>');
</script>

document.write(“
    ”); $.ajax({ url:'db_to_app_prod.php', 数据类型:“jsonp”, jsonp:'jsoncallback', 超时:5000, 成功:功能(数据、状态){ $.each(数据、函数(i、项){ document.write(“
  • ”); }); }, 错误:函数(){ text('加载数据时出错'); } }); 文件。写(“
”);
这就是结果: 正如你所看到的,布局现在完全被打破了。会发生什么?为什么?我如何解决这个问题以获得初步结果

编辑: 这是我做的另一次尝试:

$(document).ready(function(){
    $(document).bind('deviceready', function(){
        //Phonegap ready
        onDeviceReady();
    });


    //var output = document.getElementById("output");
    var _ul = document.createElement('ul');

    _ul.setAttribute("data-role", "listview");


    $.ajax({
        url: 'db_to_app_prod.php',
        dataType: 'jsonp',
        jsonp: 'jsoncallback',
        timeout: 5000,
        success: function(data, status){
            $.each(data, function(i,item){ 

                var _li =  document.createElement('li');
                _li.setAttribute("data-icon", "false");
                _li.innerHTML = '<li data-icon="false">'+
                '<a href="" id="'+item.id+'">'+
                '<img src="http://gestisciapp.it/gruppodipalo/images/'+item.img+'">'+
                '<h2>'+item.marca+'</h2>'+
                '<p class="wrap">'+item.descrizione+'</p>'+
                '<span class="ui-li-count">'+item.prezzo+' €</span>'+
                '</a></li>';    

                _ul.appendChild(_li);

            }); 

        },
        error: function(){
           output.text('There was an error loading the data.');
        }
    });
    document.getElementById("output").appendChild(_ul);

});
$(文档).ready(函数(){
$(document).bind('devicerady',function(){
//Phonegap就绪
ondevicerady();
});
//var output=document.getElementById(“输出”);
var_ul=document.createElement('ul');
_ul.setAttribute(“数据角色”、“列表视图”);
$.ajax({
url:'db_to_app_prod.php',
数据类型:“jsonp”,
jsonp:'jsoncallback',
超时:5000,
成功:功能(数据、状态){
$.each(数据、函数(i、项){
var_li=document.createElement('li');
_li.setAttribute(“数据图标”、“假”);
_li.innerHTML='
  • '+ “
  • ”; _ul.儿童; }); }, 错误:函数(){ text('加载数据时出错'); } }); document.getElementById(“输出”).appendChild(_ul); });
    类似这样的内容:

        .....
        success: function(data, status){
            var _ul = $('<ul />').attr('data-role','listview');
            $.each(data, function(i,item){ 
    
                $('<li data-icon="false" />')
                   .append($('<a href="" id="'+item.id+'" />')
                     .append('<img src="http://gestisciapp.it/gruppodipalo/images/'+item.img+'" />')
                     .append('<h2>'+item.marca+'</h2>')
                     .append('<p class="wrap">'+item.descrizione+'</p>')
                     .append('<span class="ui-li-count">'+item.prezzo+' €</span>')
                    )//$('<a />')
                //)//$('<li />') no need sorry
                .appendTo(_ul);   
            });
            $('#output').empty().append(_ul);
        },
    ....
    
    完整的工作示例 测试在谷歌移动模拟器工具

    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
        <meta charset="utf-8" />
        <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.css">
        <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js" type="text/javascript"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.js"></script>
        <script type="text/javascript">
            function getData() {
                $.ajax('tony.js?id=' + Math.random(), //fake json which match your structure
                    {
                        dataType: "json",
                        jsonp: "jsoncallback",
                        method: 'get',
                        contentType: 'application/json',
                        success: function (data, status) {
                            var _ul = $('<ul />').attr('data-role', 'listview');
                            $.each(data, function (i, item) {
                                $('<li data-icon="false" />')
                                   .append($('<a href="" id="' + item.id + '" />')
                                     .append('<img src="http://gestisciapp.it/gruppodipalo/images/' + item.img + '" />')
                                     .append('<h2>' + item.marca + '</h2>')
                                     .append('<p class="wrap">' + item.descrizione + '</p>')
                                     .append('<span class="ui-li-count">' + item.prezzo + ' €</span>')
                                    )//$('<a />')
                                .appendTo(_ul);
                            });
                            $('#output').empty().append(_ul).enhanceWithin();//.listview();
                        },
                        error: function (xhr, d, s) {
                            $('#output').empty().html(s);
                        }
                    });
            }
        </script>
    </head>
    <body>
        <button onclick="getData()">Get Data</button>
        <div id="output"></div>
    </body>
    </html>
    
    
    函数getData(){
    $.ajax('tony.js?id='+Math.random(),//与您的结构匹配的伪json
    {
    数据类型:“json”,
    jsonp:“jsoncallback”,
    方法:“get”,
    contentType:'应用程序/json',
    成功:功能(数据、状态){
    var_ul=$('
      ').attr('data-role','listview'); $。每个(数据、功能(i、项){ $(“
    • ”) .append($('') .append(“”) .append(“”+item.marca+“”) .append(“

      ”+item.descripione+”

      ) .append(“”+item.prezzo+“”€')) )//$('') .附于(_ul); }); $('#output').empty().append(_ul).enhanceWithin();/.listview(); }, 错误:函数(xhr、d、s){ $('#output').empty().html; } }); } 获取数据
    类似这样的内容:

        .....
        success: function(data, status){
            var _ul = $('<ul />').attr('data-role','listview');
            $.each(data, function(i,item){ 
    
                $('<li data-icon="false" />')
                   .append($('<a href="" id="'+item.id+'" />')
                     .append('<img src="http://gestisciapp.it/gruppodipalo/images/'+item.img+'" />')
                     .append('<h2>'+item.marca+'</h2>')
                     .append('<p class="wrap">'+item.descrizione+'</p>')
                     .append('<span class="ui-li-count">'+item.prezzo+' €</span>')
                    )//$('<a />')
                //)//$('<li />') no need sorry
                .appendTo(_ul);   
            });
            $('#output').empty().append(_ul);
        },
    ....
    
    完整的工作示例 测试在谷歌移动模拟器工具

    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
        <meta charset="utf-8" />
        <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.css">
        <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js" type="text/javascript"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.js"></script>
        <script type="text/javascript">
            function getData() {
                $.ajax('tony.js?id=' + Math.random(), //fake json which match your structure
                    {
                        dataType: "json",
                        jsonp: "jsoncallback",
                        method: 'get',
                        contentType: 'application/json',
                        success: function (data, status) {
                            var _ul = $('<ul />').attr('data-role', 'listview');
                            $.each(data, function (i, item) {
                                $('<li data-icon="false" />')
                                   .append($('<a href="" id="' + item.id + '" />')
                                     .append('<img src="http://gestisciapp.it/gruppodipalo/images/' + item.img + '" />')
                                     .append('<h2>' + item.marca + '</h2>')
                                     .append('<p class="wrap">' + item.descrizione + '</p>')
                                     .append('<span class="ui-li-count">' + item.prezzo + ' €</span>')
                                    )//$('<a />')
                                .appendTo(_ul);
                            });
                            $('#output').empty().append(_ul).enhanceWithin();//.listview();
                        },
                        error: function (xhr, d, s) {
                            $('#output').empty().html(s);
                        }
                    });
            }
        </script>
    </head>
    <body>
        <button onclick="getData()">Get Data</button>
        <div id="output"></div>
    </body>
    </html>
    
    
    函数getData(){
    $.ajax('tony.js?id='+Math.random(),//与您的结构匹配的伪json
    {
    数据类型:“json”,
    jsonp:“jsoncallback”,
    方法:“get”,
    contentType:'应用程序/json',
    成功:功能(数据、状态){
    var_ul=$('
      ').attr('data-role','listview'); $。每个(数据、功能(i、项){ $(“
    • ”) .append($('') .append(“”) .append(“”+item.marca+“”) .append(“

      ”+item.descripione+”

      ) .append(“”+item.prezzo+“”€')) )//$('') .附于(_ul); }); $('#output').empty().append(_ul).enhanceWithin();/.listview(); }, 错误:函数(xhr、d、s){ $('#output').empty().html; } }); } 获取数据
    之所以发生这种情况,是因为脚本动态注入的元素没有应用CSS。检查此帮助永远不要使用
    document.write
    来添加/更改动态上下文。@AlexKudryashev实际上,如果我对appendchild、innerhtml、append执行相同的操作,我会得到相同的结果。@Deep你能根据我的操作编写正确的代码吗?在“动态”中示例:您没有创建opening
    ul
    标记。这是因为CSS没有应用于脚本动态注入的元素。检查此帮助永远不要使用
    文档。编写
    来添加/更改动态上下文。@AlexKudryashev实际上,如果我对appendchild、innerhtml、append执行相同的操作,我会得到相同的结果。@Deep你能根据我的操作编写正确的代码吗?在你的“动态”示例中,你没有创建opening
    ul
    标记。现在它什么也不打印?如果我使用json而不是jsonp,它就会失败(我有另一个更简单的ajax,可以与jsonp配合使用)。不管怎么说,你发布的这段代码根本没有结果……你能检查一下吗?php页面生成了这个结果:
    ([{“id”:“35”,“marca”:“Pr