zl程序教程

您现在的位置是:首页 >  后端

当前栏目

html+js+php一次原始的Ajax请求示例

JSPHPHTMLAJAX 示例 一次 请求 原始
2023-06-13 09:15:24 时间
今天给大家呈现一个原始的Ajax请求过程,虽然jquery的ajax要比原始的写法容易得多,我们还是应该了解原始的写法,下面我分为html、js、php三个小文件来展示,数据库自己写。

首先是html:
复制代码代码如下:

<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
<title>一次简单的Ajax请求</title>
<scriptlanguage="javascript"src="js/ajaxTest.js"></script>
</head>
<body>
用户名:<inputid="userName"type="text"></input>
密码:<inputid="passWord"type="password"></input>
<spanid="showInputError"style="color:red;font-weight:bold;"></span><br>
<inputtype="button"value="登录"onclick="showSelect()">
</body>
</html>

然后是js:
复制代码代码如下:

/**
*普通Ajax的完整访问过程
*/
varxmlHttp

functionshowSelect()//登录按钮点击后执行这个方法
{
varuserName=document.getElementById("userName").value;
varpassWord=document.getElementById("passWord").value;
if(userName.length==0)//验证输入用户名是否为空
{
document.getElementById("showInputError").innerHTML="用户名不能为空";//提示用户名不能为空
return
}
xmlHttp=GetXmlHttpObject()
if(xmlHttp==null)
{
alert("BrowserdoesnotsupportHTTPRequest")
return
}
varurl="ajaxTest.php"//设置要提交action到后台的那个处理请求的文件名
url=url+"?userName="+userName+"&passWord="+passWord//为这个路径加上参数用户名和密码
url=url+"&sid="+Math.random()//为这个路径加上一个随机数
xmlHttp.onreadystatechange=stateChanged//每当readyState改变时,就会触发onreadystatechange事件,readyState属性存有XMLHttpRequest的状态信息
xmlHttp.open("GET",url,true)//定义请求的参数
xmlHttp.send(null)//发送请求
}

functionstateChanged()
{
if(xmlHttp.readyState==4||xmlHttp.readyState=="complete")//
//0:请求未初始化
//1:服务器连接已建立
//2:请求已接收
//3:请求处理中
//4:请求已完成,且响应已就绪
{vara=xmlHttp.responseText;//把相应数据赋值给a
if(a=="yes"){
self.location="Main.php";//跳转到Main.php
}else{
document.getElementById("showInputError").innerHTML="用户名或密码错误";//提示用户名或密码错误
}
}
}
functionGetXmlHttpObject()
{
varxmlHttp=null;
try
{
//Firefox,Opera8.0+,Safari
xmlHttp=newXMLHttpRequest();
}
catch(e)
{
//InternetExplorer
try
{
xmlHttp=newActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
xmlHttp=newActiveXObject("Microsoft.XMLHTTP");
}
}
returnxmlHttp;
}

最后是php:
复制代码代码如下:
<?php
$userName=$_GET["userName"];
$pwd=$_GET["passWord"];
$con=mysql_connect("localhost","root","123456");
mysql_select_db("my_test",$con);
mysql_query("setnamesutf8");
$sql="SELECT*FROMUserinfoWHEREuserName="".$userName.""ANDpwd="".$pwd.""";
$result=mysql_query($sql);
$select=mysql_num_rows($result);
$a="no";
if($select>0){$a="yes";}
echo$a;
mysql_close($con);
?>