【问题标题】:jQuery not working after $ajax call$ajax 调用后 jQuery 不工作
【发布时间】:2014-03-31 00:50:36
【问题描述】:

我正在尝试使用 jQuery $.post 方法从 php 文件中获取数据。在 ajax 调用之后,我从 php 文件中添加了一个按钮,该按钮将通过删除自身来加载更多帖子,但是在 ajax 调用之后,jQuery 不再工作。

var result = function (str,end)
{
    $.get("query.php",{ start:str, end: end },function(ajaxresult){
    $(ajaxresult).appendTo(".focus");  
    })
}
result(4,0);

$('#loadmore').on('click', function(e){
    result(8,4);
    alert('delete');
    e.preventDefault();
    e.remove();
});

Here is my Php file code.

<?php
$start = $_GET['start'];
$end = $_GET['end'];


$con = mysqli_connect('localhost','root','binarystar','test');
if (!$con)
{
    die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"users");
$sql="SELECT * FROM post ORDER BY id DESC LIMIT $end,$start";

$result = mysqli_query($con,$sql);


while($row = mysqli_fetch_array($result))
{
    echo "<section>";
    echo "<span class='feed_username'>" . $row['username'] ."</span>   ";
    echo "<span class='date'>" . $row['time'] ."</span><br>";
    echo "<span class='postx'>" . $row['post'] ."</span><br>";
    echo "</section>";

}
echo "<button id='loadmore'>Load More Posts</button>";

mysqli_close($con);

【问题讨论】:

  • 这与您的问题无关,但请考虑在执行 MySQL 查询时使用 PDO 来提高安全性和性能。 us2.php.net/pdo_mysql

标签: jquery ajax


【解决方案1】:

由于id 是唯一的,你需要使用类来代替:

echo "<button class='loadmore'>Load More Posts</button>";

然后你可以使用 event delegation 来动态加载元素:

$('body').on('click', '.loadmore', function() {
    // Your code here
});

【讨论】:

  • 你怎么知道按钮不在 .focus 中,并且被新内容覆盖,这样 ID 在文档中是唯一的?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-15
  • 2019-01-15
  • 1970-01-01
  • 1970-01-01
  • 2014-08-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多