使用 jQuery 刷新 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16874668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Refresh a div with jQuery
提问by nimrod
Is it possible to refresh a single div with jQuery? I have a button that does logout a user. After the button is clicked, I want to show the login form, so I need to re-parse this div.
是否可以使用 jQuery 刷新单个 div?我有一个按钮可以注销用户。点击按钮后,我想显示登录表单,所以我需要重新解析这个div。
The content of my div is this:
我的 div 的内容是这样的:
<div id="signup" class="register">
<?php
$email = $_COOKIE['email'];
$login = $_COOKIE['login'];
if($email != null && $email != "" && $login != null && $login != "") {
echo "<h3>you are logged in as <b>$email</b></h3><br><br><button id='logoutbtn' class='submitButton'>Logout</button>";
} else {
// show login form
}
?>
</div>
This is my JavaScript part where I perform the logout:
这是我执行注销的 JavaScript 部分:
$('#logoutbtn').click(function () {
$.ajax({
type: "POST",
url: "php/logout.php",
async: false,
success: function(data){
// reload signup div
}
});
});
Edit: My logout.php script removes the cookies, that's why I need to re-parse the signup-div.
编辑:我的 logout.php 脚本删除了 cookie,这就是为什么我需要重新解析 signup-div。
采纳答案by Lucas
You can dynamically change the contents of the signup div with jquery as follows:
您可以使用 jquery 动态更改注册 div 的内容,如下所示:
$("#signup").html("My New Login Section");
or
或者
var $loginDiv = $(document.createElement("div")).html("<label>Username</label><input type='text' id='username'/>");
$("#signup").html($loginDiv);
回答by Frederik.L
I'd try:
我会尝试:
$('#logoutbtn').on('click', function () {
$.ajax({
type: "POST",
url: "php/logout.php"
})
.done(function(data){
$('#signup > h3').html('Please <button id="loginbtn" class="submitButton">Login</button>');
});
})
The same approach could be used for the login action to prevent the page from having to refresh.
相同的方法可用于登录操作,以防止页面必须刷新。
回答by eddy52
as you have your session method inside of your tag, you can do on success event following:
当您的标签中有会话方法时,您可以在成功事件中执行以下操作:
success: function(data){
$("#signup").load(".register");
}
it will reload everything inside of < div id="signup" class="register"> and as you've removed your session (i suppose), than it will be reload to your login/logout form.
它将重新加载 <div id="signup" class="register"> 内的所有内容,并且当您删除会话时(我想),它会重新加载到您的登录/注销表单。