[英]How to execute a php header script from javascript?
I have the following script validation.php
我有以下脚本
validation.php
<?php
if(!isset($_SESSION['userId'])){
session_destroy();
header('Location: home.php');
exit;
}
?>
I would like to execute this script every time someone clicks a button in the #main-display
每当有人点击
#main-display
的按钮时,我想执行此脚本
$("#main-display").on('click', 'button', function (event){
//some code in here
});
How would I go about doing this? 我该怎么做呢?
You cant do a redirect from within a ajax request directly since it will only redirect the response page to home.php and not the current main DOM window. 您无法直接从ajax请求中进行重定向,因为它只会将响应页面重定向到home.php而不是当前的主DOM窗口。
You are going to have to modify it to something like this in the php: 您将不得不在php中将其修改为类似的内容:
if(!isset($_SESSION['userId'])){
session_destroy();
$response['status'] = 'false';
}
else {
$response['status'] = 'true';
}
echo json_encode($response);
And then on the javascript 然后在JavaScript上
$("#main-display").on('click', 'button', function (event){
$.getJSON('/path/to/loginStatus.php', {}, function(response) {
if(response.status == 'false') {
location.href = 'home.php';
}
});
});
To start from the simplest, $.get('validation.php')
is enough to get your script to run, but to do something useful with it you 'll need to provide more context. 从最简单的开始,
$.get('validation.php')
足以让你的脚本运行,但是为了做一些有用的事情,你需要提供更多的上下文。 For the most generic "do-everything" method with bazillions of options, see $.ajax
; 对于使用bazillions选项的最通用的“do-everything”方法,请参阅
$.ajax
; everything else is a subset of this¹. 其他一切都是这个¹的一个子集。
¹ This is not strictly true, but there are only a couple of minor exceptions that you shouldn't care about at this point . ¹ 这不是严格意义上的,但目前只有几个小的例外情况你不应该关心 。
Try this .. 尝试这个 ..
$("#main-display").on('click', 'button', function (event){
$.get("validate.php",function(data){
alert("response is "+data);
});
});
$('#main-display').click(function(){
$.get('validate.php');
});
Hope this works! 希望这个有效!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.