新手求教ajax设置session的问题

oSuperkinG 2014-02-17 11:24:47
这是js代码:
            function searchbutton(){
var str = document.getElementById("textarea").value;
if(str != null){
alert(str);
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
window.location.href = "function/search.php";
}
}
xmlhttp.open("get","function/search.php?text="+str,true);
xmlhttp.send();
}
}


这是处理请求的页面:
<?php
session_start();
$_SESSION['searchtext'] = $_GET["text"];
echo "欢迎来到搜索界面!";
echo "您搜索的内容为:".$_SESSION["searchtext"];
?>


为何跳转到search.php页面后,session还是空?if(xmlhttp.readyState == 4 && xmlhttp.status == 200)这句话不是说响应已经就绪才会跳转吗?请前辈告诉我我那里理解错了?
...全文
200 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
oSuperkinG 2014-02-17
  • 打赏
  • 举报
回复
千万不要沉啊
snow_finland 2014-02-17
  • 打赏
  • 举报
回复
xmlhttp.onreadystatechange = function(){ if(xmlhttp.readyState == 4 && xmlhttp.status == 200){ window.location.href = "function/search.php"; } } 这里第三行的跳转有问题, search.php 页面中有 $_SESSION['searchtext'] = $_GET["text"]; 但是通过这个 window.location.href = "function/search.php"; 跳转过去的时候,没有带“?text=abc”的参数传过去,自然$_GET["text"]就取不到内容了,那$_SESSION['searchtext']就会是空了。 ps:ajax一般请求完成后,通过返回的数据在本页面做操作,而不是通过页面跳转来查看请求是否成功, 比如:可以在页面同页面,id叫result的容器里输出结果: 这时把window.location.href = "function/search.php";这行改成 document.getElementById("result").innerHTML = xmlhttp.responseText; 即可看到结果。

52,797

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 Ajax
社区管理员
  • Ajax
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧