ajax基本使用

ajax的使用就是写好4条线

1.创造一个ajax搜索引擎

  

function ajaxObject()
{
var xmlHttp;

if(window.ActiveXObject)
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
xmlHttp = new XMLHttpRequest();
}

return xmlHttp;
}

 

2.html请求

var xmlHttpRequest;

这里分为两种传送

post,get

其中post必须加上一句:xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

两种格式代码分别如下:

post方式:

 

function userNameCheck()
{
xmlHttp = new ajaxObject();

if(xmlHttp)
{
var url = "/php/ajax/register/usernamecheke.php";
xmlHttp.open("get",url,true);
xmlHttp.onreadystatechange = raplyFunction;
var data = "username=" + $("username").value;
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//必须加的
xmlHttp.send(data);
}
}

 

get方式:

function usernamecheke()
{
xmlHttpRequest = getXmlHttpObject();

if(xmlHttpRequest)
{
var url = "/php/ajax/register/usernamecheke.php?username=" + $("username").value;

xmlHttpRequest.open("get",url,true);

xmlHttpRequest.onreadystatechange = chuli;

xmlHttpRequest.send(null);



}
}

3.后台处理

<?php
//3号线
header("Cache-Control:no-cache");//禁用缓存
header("Content-Type:text/html; charset=gb2312");//定义字符编码
$username = $_POST['username'];//若用Get发送数据,这里改成$username = $_GET['username'];
if($username=="shichangyi110")
{
echo "该用户已被使用";
}
else
{
echo "该用户可以注册";
}
?>

 

4.处理结果,回调函数处理

function raplyFunction()
{

if(xmlHttp.readystate==4)
{
var span = document.getElementById("myres");
//alert(div.tagName);
span.innerHTML = xmlHttp.responseText;
var res = xmlHttp.responseText;
if(res.value=="该用户已被使用")
{
span.style.color = "red";
}
else
{
span.style.color = "green";
}
}
}

 

posted @ 2013-03-02 00:48  幽幽他爸  阅读(201)  评论(0编辑  收藏  举报