我想将path
变量从js传递到plus-page.php
,然后转到该页面。
$("#btnpage").click(function(){
path = $('#spantwrap').html();
console.log(path); // works, that's a simple html code.
$.ajax({
url: 'plus-page.php',
type: 'post',
data: {'path': path},
success: function() {
console.log(path);
}
});
location.href = 'plus-page.php';
});
加page.php文件
<form id="form1" action="?" method="post">
<input type="hidden" name="path" value="<?php echo $_POST['path'];?>" // line 46
</form>
错误:Undefined index: path on line 46...
答案 0 :(得分:3)
问题是你是立即重定向,而不是在重定向中传递变量。由于您立即重定向,正在进行的ajax调用永远不会真正启动并几乎立即终止。
完全删除你的ajax调用并设置如下位置:
location.href = "plus-page.php?path=" + encodeURIComponent(path);
...并使用$_GET['path']
代替$_POST['path']
。
或者,如果确实想首先进行ajax调用,请在转到新页面之前等待它完成:
$.ajax({
url: 'plus-page.php',
type: 'post',
data: {'path': path}, // Side note: The ' here are unnecessary (but harmless)
success: function() {
location.href = 'plus-page.php'; // You might or might not add path here as
// above, it's unclear why you'd do the
// ajax then redirect
console.log(path);
}
});
答案 1 :(得分:2)
解决方案当然是摆脱ajax调用,只是将表单发布到plus-page.php
,因为它在当前形式中没有任何意义
但是如果你真的想拥有这个逻辑,即将一些变量传递给第二页并稍后重定向到该页面,那么你应该在会话中保留传递的值并在以后使用它
<?php
if (isset($_POST['path'])
{
$_SESSION['path'] = $_POST['path'];
// to stop only in case of AJAX call use the following line:
// if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
die();
}
?>
<form id="form1" action="?" method="post">
<input type="hidden" name="path" value="<?php echo $_SESSION['path'];?>" // line 46
</form>
请注意,如果您想重定向immediataly
,这没有任何意义答案 2 :(得分:1)
请改为尝试:
$("#btnpage").click(function(){
path = $('#spantwrap').html();
console.log(path); // works, that's a simple html code.
var form = document.createElement("form");
var element1 = document.createElement("input");
form.method = "POST";
form.action = "plus-page.php";
element1.value=path;
element1.name="path";
form.appendChild(element1);
document.body.appendChild(form);
form.submit();
});
这会创建一个表单,将路径作为输入添加到表单并提交表单。