在输出数据时,脚本无法正常运行

时间:2016-09-08 15:44:23

标签: javascript php html

昨天晚上,我想出了如何输出数据,从我的索引页面上的表单发送到我的内容页面,然后将我的内容div中的结果显示在我的索引页面上。

但现在我遇到了一个新问题。我的Javascript不会将其函数(renderGrid)应用于我的内容div,除非我弄乱了视口,因为那时window.addEventListener(" resize",renderGrid,false);发挥作用。

我不知道如何解释它。

谢谢,

index.html

<form id="search_form" action="content.php" method="POST">           
   <input id="form_search" type="search" name="name">               
   <input id="form_submit" type="submit" name="submit" value="Enter">
</form>

<div id="content"></div>

JS

$(document).ready(function(){
    var form = $('#search_form');
    form.submit(function(event){
        var form_search = $('#form_search').val();
        if($.trim(form_search) != '') {
            $.post("content.php", {name: form_search}, function(data){
                $('#content').html(data);       
            });
        }
        event.preventDefault();
    });
});

function renderGrid(){

var blocks = document.getElementById("content").children;
var pad = 20, cols = 3, newleft, newtop;
for(var i = 1; i < blocks.length; i++){
    if(i % cols == 0){
        newtop = (blocks[i-cols].offsetTop + blocks[i-cols].offsetHeight) + pad;
        blocks[i].style.top = newtop+"px";
    }else{
        if(blocks[i-cols]){ 
            newtop = (blocks[i-cols].offsetTop + blocks[i-cols].offsetHeight) + pad;
            blocks[i].style.top = newtop+"px";
        }
        newleft = (blocks[i-1].offsetLeft + blocks [i-1].offsetWidth) + pad;
        blocks[i].style.left = newleft+"px";
    }
    }
}
window.addEventListener("load", renderGrid, false); 
window.addEventListener("resize", renderGrid, false);

content.php

<?php
include ("connect.inc.php");
$userinput = $_POST['name'];
$query = "SELECT * FROM xxx WHERE xxx LIKE '%$userinput%'";
$result = mysqli_query($db_link, $query) or die(mysqli_error($db_link));
while($row = mysqli_fetch_assoc($result)){  
?>

<article>
    <?php echo $row['xxx'];?>
</article>

<?php 
}
?>

Picture 1 = This is what it does. (When I submit Russia, my query will get me two results, but as you can see, these results are now on top each other upon output. This is because the JavaScript is unaware, that I have outputted something.)

Picture 2 = This is what it should look like, when outputted. (Now, if I mess with the viewport, such as open inspect, my JavaScript begins to work (window.addEventListener("resize", renderGrid, false);), so my JavaScript works, but not when I output data, but not automatically when I output data.)

1 个答案:

答案 0 :(得分:0)

当您的对象(load)完成加载时,

window事件(如manual中所示)将触发。加载一些ajax内容时,不会触发此事件。因此,您应该明确地致电renderGrid

$.post("content.php", {name: form_search}, function(data){
    $('#content').html(data);       
    renderGrid();
});