gpt4 book ai didi

javascript - 从 PHP 更新 DIV 标签

转载 作者:行者123 更新时间:2023-11-28 18:07:01 25 4
gpt4 key购买 nike

我是一名新开发人员。我已经阅读了很多有关我的主题的问题,并且看到了很多有趣的答案,但不幸的是,我找不到解决我的问题的方法。我有一个简单的 HTML 表单和 <div id="comment"></div>其中(如果没有任何内容可传递给用户,则为空)。该 DIV 应该向用户提供更新,例如 Wrong Username or Password!当这种情况发生时。该表单通过 PHP 和 MySQL 进行处理。

    ...
$result = mysqli_query($idConnect, $sql);

if (mysqli_num_rows($result) > 0) {

mysqli_close($idConnect);
setCookie("myapp", 1, time()+3600 * 24 * 60); //60 days
header("Location: ../main.html");
} else {
//Please update the DIV tag here!!
}
...

我尝试从 jQuery(使用 AJAX)“读取”PHP,但无论我没有解决方案,还是无法以这种方式完成...我在 jQuery 中使用了它( #login 是形式):

$("#login").submit(function(e){
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url : formURL,
type: "POST",
data : postData,
success:function(data) {
$("#comment").replaceWith(data); // You can use .replaceWith or .html depending on the markup you return
},
error: function(errorThrown) {
$("#comment").html(errorThrown);
}
});
e.preventDefault(); //STOP default action
e.unbind();
});

但我想更新 DIV 标签 #comment如果凭据错误,则会显示一些消息。但考虑到 PHP 正在处理表单,我不知道如何更新该 DIV...

你能帮忙吗?

提前致谢! :)

最佳答案

为了使 AJAX 正常工作,PHP 必须回显 AJAX 调用返回的内容:

if (mysqli_num_rows($result) > 0) {

mysqli_close($idConnect);
setCookie("myapp", 1, time()+3600 * 24 * 60); //60 days
echo 'good';
} else {
//Please update the DIV tag here!!
echo 'There is a problem with your username or password.';
}

但这不会显示在error: function中,因为当AJAX本身出现问题时会使用该函数。此文本将在成功回调中返回,因此您必须在那里更新 div:

success:function(data) {
if('good' == data) {
// perform redirect
window.location = "main.html";
} else {
// update div
$("#comment").html(data);
}
},

此外,由于您使用 AJAX 调用 PHP,因此 header("Location: ../main.html"); 将不起作用。您需要根据状态将 window.location 添加到成功回调中。

关于javascript - 从 PHP 更新 DIV 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42368347/

25 4 0