php ajax异步请求实现,PHP----Ajax异步请求

需要两个PHP页面:1.php是发出请求和接受请求结果的。2.php是处理请求的结果。

1.php中代码:

要有能触发JS中函数的标签,这里是a标签。在1.php页面中有JS代码进行请求:

var http_request=false;

function sendAjaxRequest(){

//alert('进入执行SEND');

//执行前先进行清理上次的结果操作

SetHidden();//这里模拟各种对页面的操作

if(window.XMLHttpRequest)//请求对象是JavaScript中的对象XMLHttpRequest。

{

http_request=new XMLHttpRequest();

}else if(window.ActiveXObject){

try

{

http_request=new ActiveXObject("Msxml2.XMLHTTP");//IE

}catch (e){

try{

http_request=new ActiveXObject("Microsoft.XMLHTTP");//ForeFox

}catch(e){}

}

}

if(http_request)

{

http_request.open("POST","2.php",true);//指定请求处理页和请求方式及是不是异步

http_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');//设置请求头,应该还能设置其他请求头部信息

var postdata="keyword="+encodeURI(document.getElementById("keyword").value);//POST的数据,如果是GET方法就不用这里了

http_request.onreadystatechange = updatePage;//页面2.php交互请求时,指定函数updatePage来处理页面2.php的响应,有5种响应,所以要进行选择处理

http_request.send(postdata);//发送POST数据

}

}

function updatePage(){//此函数根据2.php所做的反应,来对页面1.php作出一些动作

if(http_request.readyState==4)//有5种响应0--4,最后一种4是处理完请求

{

//alert('响应已完成,可以访问服务器响应并使用它');

//alert(http_request.responseText);

var div=document.getElementById("divresult");

if(http_request.responseText.split(';')[0]!=""&&http_request.responseText.split(';')[0]!=undefined&&http_request.responseText.split(';')[1]!=undefined)

{

document.getElementById("label3").innerHTML=http_request.responseText.split(';')[0]+" ";

document.getElementById("label5").innerHTML=http_request.responseText.split(';')[1]+" ";//这里responseText,是页面2.php echo函数打印的所有数据

div.style.display="block";

}

else

{

alert("2.php处理完了");

}

}

}

function SetHidden(){

document.getElementById("divresult").style.display="none";

}2.php中的响应:

$link=mysql_connect("192.168.100.100","ccc","ccc");

if($link)

{

$db_select=mysql_select_db("search",$link);

mysql_query("set names utf8");

}

if($db_select)

{

$result=mysql_query("select proname,person from search where APPKEY='".$_POST[keyword]."'",$link);

mysql_close($link);

}

if($result)

{

$info=mysql_fetch_array($result);

mysql_free_result($result);

}

if($info)

{

echo $info[proname];//最主要是输出的内容,是与1.php进行交互的基础,另一种交互的方法是用GET和POST请求对1.php再次发出,1.php进行接收请求

echo ";".$info[1];

}

?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值