![](/img/trans.png)
[英]Sending post request using ajax and load the data into the same php file
[英]AJAX post data to PHP file and redirect to the same file to echo post data
我有一个PHP文件,其中有一堆包含用户名的<a></a>
元素。 单击这些链接之一后,链接的data
属性将存储并通过AJAX发布到第二个php文件。 但是,一旦我重定向到该文件,就不会显示我发布的值,而是得到错误: Undefined index userid
。
这是我的代码:
的index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Post Test</title>
</head>
<body>
<a href="#" class="user-name" data-user-id="1" data-render-view="users.php">User 1</a>
<a href="#" class="user-name" data-user-id="2" data-render-view="users.php">User 2</a>
<a href="#" class="user-name" data-user-id="3" data-render-view="users.php">User 3</a>
<a href="#" class="user-name" data-user-id="4" data-render-view="users.php">User 4</a>
<a href="#" class="user-name" data-user-id="5" data-render-view="users.php">User 5</a>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$('.user-staff').on('click',function(){
var userid = $(this).data('user-id');
var renderView = $(this).data('render-view');
$.ajax({
url: "users.php",
type: "POST",
data: {userid:userid},
success: function(data, textStatus, jqXHR){
window.location = renderView;
},
error: function (jqXHR, textStatus, errorThrown){
alert('Error!')
}
});
});
</script>
</body>
</html>
Users.php
<?php
$userIdExchanged = $_POST['userid'];
echo '<h1>user profile page</h1>';
echo $userIdExchanged; //Nothing is outputted here.
?>
是的,那确实是发生了什么,基本上,第一步,您发送了一个ajax请求,并发送了该值user-id
。
然后,您重定向。 这意味着您有两个单独的请求。
第一个请求成功。 重定向后(第二个出现),因为第一个请求上的数据没有持久化 ,所以您的值不再存在。
我不知道您为什么要提出ajax请求。 最好也可以正常提交表格。
但是,如果您真的想继续学习此课程,则在第一个请求(ajax请求)上,可以将其保存在会话中。
这样您发送的值将被保存。 然后,在重定向之后,您仍然可以访问它:
<script type="text/javascript">
// maybe you mean `.user-name` not `.user-staff`
$('.user-name').on('click',function(){
var userid = $(this).data('user-id');
var renderView = $(this).data('render-view');
$.ajax({
url: "users.php",
type: "POST",
data: { userid: userid, setid: true }, // add a flag
success: function(data, textStatus, jqXHR){
window.location = renderView;
},
error: function (jqXHR, textStatus, errorThrown){
alert('Error!')
}
});
});
</script>
然后在PHP中:
<?php
session_start();
// if the set flag is used, set it
if(isset($_POST['setid'])) {
$_SESSION['userid'] = $_POST['userid'];
}
// if no flag is set, then this will just continue and echo the value currently set
$userIdExchanged = $_SESSION['userid'];
echo '<h1>user profile page</h1>';
echo $userIdExchanged;
?>
html标记中的类名是“用户名”,但是您正在侦听.js中对“用户工作人员”类名的单击。 不确定这只是错字...
<a href="#" class="user-name" ......
$('.user-staff').on('click',function(){....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.