[英]Can I use jQuery and AJAX to execute php code written in the same file?
I searched a lot and all I found out was that AJAX is used to execute a php code in another file. 我进行了很多搜索,发现所有内容都是使用AJAX在另一个文件中执行php代码。 I want to know if it is possible and if yes then how do I execute a php code that is written in the same file.
我想知道是否有可能,如果可以,那么我如何执行写在同一文件中的php代码。
Here is my jQuery code... 这是我的jQuery代码...
$(document).ready(function(){
$("#logout").click(function(){
//execute the php code here.
});
});
And here is the php code i want to execute 这是我要执行的php代码
<?php
session_unset();
session_destroy();
?>
Basically, to give an overview of what I am trying to achieve, I am using a button with id="logout" to stop the session and logout of the webpage. 基本上,为了概述我要实现的目标,我使用一个带有id =“ logout”的按钮来停止会话和退出该网页。
In short, yes, you can use ajax to run some php code that was found in the same file that was used to render the page you are viewing. 简而言之,是的,您可以使用ajax运行一些php代码,这些代码在用于呈现正在查看的页面的同一文件中找到。
You may want to go a different route in this case since logging out usually means that some of the items that a user can see on the page should no longer be accessed by the user. 在这种情况下,您可能需要走另一条路,因为注销通常意味着用户不应再访问页面上用户可以看到的某些项目。 Implementing the logout button as a link that reloads the entire page can be a good way to go.
将注销按钮实现为重新加载整个页面的链接,可能是一个不错的方法。
To accomplish what your question details, you could add this php at the top of your page. 要完成您的问题的详细信息,您可以在页面顶部添加此php。
if ( isset( $_POST['logout'] ) ) {
session_unset();
session_destroy();
die();
}
This way, a post request with a logout parameter will trigger this code. 这样,带有注销参数的发布请求将触发此代码。 Now in the jQuery, you need to send a post to this url with the logout parameter set.
现在,在jQuery中,您需要发送带有注销参数集的此URL的帖子。
let data = {
'logout' : true
};
$.post( window.location, data );
Checkout https://api.jquery.com/jquery.post/ and https://api.jquery.com/jQuery.ajax/ for more info. 检出https://api.jquery.com/jquery.post/和https://api.jquery.com/jQuery.ajax/了解更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.