Ajax用法

来源:互联网 发布:福利ios直播软件 编辑:程序博客网 时间:2024/05/22 12:47

Ajax原理图:



html,javascript,php

html提交给javascript

javascript提交php,并用一个方法用于处理php处理后返回的数据,该方法用于显示结果


例如

html

通过

<input type="text" name="yzm" value="" size="20" maxlength="40"  onblur="javascript:vcode_check('yzm')" onkeyup="javascript:vcode_check('yzm')"/>

提交给javascript,中的vcode_check('yzm')方法

在该方法中

调用DealData方法

GetXmlHttpObject();
var str=document.getElementById(id).value;
var url="ajaxs/vcode_check.php?vocode="+str;//传递变量vocode,str是html的值
xmlHttp.onreadystatechange=DealData;//处理的方法
xmlHttp.open("GET",url,true);//用给的方式
xmlHttp.send(null);


php文件用

$vocode=$_GET["vocode"];

来获取待处理的数据变量

function DealData(){
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 {
  if(xmlHttp.responseText=="0"){document.getElementById("vcode_tx").innerHTML="value=0";}
  else if(xmlHttp.responseText=="1"){document.getElementById("vcode_tx").innerHTML="value=1";}
  else if(xmlHttp.responseText=="2"){document.getElementById("vcode_tx").innerHTML="value=2";}
 }
}


常见问题:

验证码刷新:onclick="javascript:this.src='ajaxs/vcode.php?image='+new Date().getTime();"

转码:header('Content-Type:text/html;charset=GB2312');

传递变量:

var url="ajaxs/vcode_check.php?vocode="+str;
xmlHttp.onreadystatechange=DealData;

var xmlHttp;
function GetXmlHttpObject()
{
try{// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{// Internet Explorer
  try{xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");}
  catch (e){xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}
  }
  if(!xmlHttp){
  alert("Cant Not Create XMLHttpRequest Object,Please Choose Other Brower");
  }
return xmlHttp;
}