gpt4 book ai didi

javascript - 仅在 Ajax POST 请求期间单击按钮时页面刷新

转载 作者:行者123 更新时间:2023-12-03 09:22:49 24 4
gpt4 key购买 nike

我是网络开发的初学者,正在构建一个简单的查询-答案网络应用程序,其中用户在文本字段中输入查询并单击按钮,JavaScript 将 POST 请求发送到服务器,服务器发回响应。现在,此响应应显示在屏幕上,直到用户输入新查询并再次单击按钮。

这是客户端代码

$(document).ready(function() {
$("button").click(function() {
$.post("ServletServer", {
Query: document.getElementById("query").value
},
function(data, status) {
var json_x = $.parseJSON(data);
$.each(json_x, function(index, element) {
$('#Results').append($('<div>', {
text: index+" "+element.URI
}));
});
});
});
});

当我尝试使用之前一些问题中提到的 window.location.reload() 时,如下所示:

$("button").click(function() {
window.location.reload()
});

显示响应后立即刷新页面。我希望响应保留在页面上,直到用户再次单击按钮。谁能告诉我哪里出错了

最佳答案

您需要在使用 $('#Results').html(""); 执行 POST 请求之前清除结果 div

$(document).ready(function(){
$("button").click(function(){
$('#Results').html(""); // clears the results, then does the ajax request.

$.post("ServletServer",
{
Query: document.getElementById("query").value
},
function(data, status){
doRequest = false; // update flag
var json_x = $.parseJSON(data);
$.each(json_x, function(index, element) {
$('#Results').append($('<div>', {
text: index+" "+element.URI
}));
});
});
});
});

关于javascript - 仅在 Ajax POST 请求期间单击按钮时页面刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31796595/

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