gpt4 book ai didi

javascript - AJAX 强制页面刷新(但不应该)

转载 作者:行者123 更新时间:2023-12-02 18:13:49 25 4
gpt4 key购买 nike

使用 JQuery 的简单 AJAX 测试页面。显示的页面最初显示按钮(BUTTON1)。单击后,它将通过 script.js 运行react.php。 React.php将通过span元素将BUTTON1替换为BUTTON2。所有这些都有效。

这里就是出错的地方。单击 BUTTON2 应该通过 script2.js 运行react2.php。然后,react2.php 应将 BUTTON2 替换为文本“SUCCESS”。但是,当单击 BUTTON2 时,页面会刷新(并再次显示 BUTTON1),而不是这样做。

当初始beginning.php页面上的按钮类从button1更改为button2时,按钮成功替换为react2.php中的字符串。我无法探究到底。

如何防止刷新以使页面在 span 元素中显示“SUCCESS”?提前致谢!

开始.php

 <html>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="script2.js"></script>
<?php
echo "<span class='span_display'>
<a href='' id='button1' class='button1'>BUTTON1</a>&nbsp;
</span>";
?>
</html>

脚本.js

$(function() {
$(".button1").click(function() {
$.ajax({
url: "react.php",
cache: false,
success: function(html) {
$(".span_display").html(html);
}
});
return false;
});
});

script2.js

...(all the same except)
url: "react2.php",

react.php

<?php
echo "<a href='' id='button2' class='like_button2'>BUTTON2</a>&nbsp;";
?>

react2.php

<?php
echo "SUCCESS";
?>

最佳答案

您的问题是由于第二个链接上缺少点击处理程序造成的,因为它是通过 ajax 动态添加的。一般建议使用 delegated events而不是将处理程序直接附加到元素:

function handler(uri) {
$.ajax({
url: uri,
cache: false,
success: function(html) {
$(".span_display").html(html);
}
});
}

$(document)
.on("click", "#button1, #button2", function(e) {
e.preventDefault();
var uri = $(this).hasClass("button1") ? "react.php" : "react2.php";
handler(uri);
});
});

jQuery documentation解释得很精彩,所以我就引用它:

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.

In addition to their ability to handle events on descendant elements not yet created, another advantage of delegated events is their potential for much lower overhead when many elements must be monitored.

关于javascript - AJAX 强制页面刷新(但不应该),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19483133/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com