您的位置:首页 > 其它

关于ajax的问题

2015-11-03 20:50 239 查看
今天 学了一点ajax 遇到了很多问题 ,现总结如下:

1 . xmlHttp.open() 里参数为true 与false的选择 true 就是异步处理 false 就是同步处理 就是当客户端请求服务时 不管服务器端是否处理完毕 就返回响应值这是异步 反之 就是同步.

2.关于我的status 值一直为0 的问题 首先 有两种可能 一种是你的网页是在本地浏览的 导致为0 还有一种就是 你的提交按钮时 submit 使得找不到了。

3. 判断state 后还要判断status 否则就会出现2的问题

4.我出现的responseText一直弹出为空就是 2 的问题

下面是我的登录完整代码

login.html

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="content-type" content="text/html; charset=utf-8">

<title>管理员登录</title>

<link rel="stylesheet" href="css/LoginCss.css" type="text/css" media="screen" charset="utf-8">

<script>

function getxmlHttpRequest()

{

var xmlHttp=null;

if (window.XMLHttpRequest)

{// code for IE7, Firefox, Mozilla, etc.

xmlHttp=new XMLHttpRequest();

}

else if (window.ActiveXObject)

{// code for IE5, IE6

xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");

}

if(xmlHttp==null)

{

alert("Your browser does not support XMLHTTP.");

}

return xmlHttp;

}

var xmlHttp=getxmlHttpRequest();

function AjaxRequst()

{

var username=document.getElementById('username').value;

var password=document.getElementById('psw').value;

sendRequest('login.php',call_back,'username='+username+'&password='+password);

}

function sendRequest(url,call_back,data)

{

var data=data || "";

xmlHttp.onreadystatechange=call_back;//onreadystatechange 在发生前和发生后都会触发,要根据 readyState 判断当前状态(只有在 readyState == 4 时才是发送完)

if(data!="")

{

xmlHttp.open("post",url,true);

xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");

xmlHttp.setRequestHeader("Content-length",data.length);

xmlHttp.setRequestHeader("Connection","close");

}else{

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

}

xmlHttp.send(data);

}

function call_back()

{

if(xmlHttp.readyState==4)

{

if(xmlHttp.status==200)

{

var res=xmlHttp.responseText;

alert(res);}

}

}

</script>

</head>

<body>

<form method="post" >

<span>管理员登录</span>

用户名:<input type="text" name="username" value="" id="username"><br/><br/>

密码:<input type="password" name="password" value="" id="psw"><br/><br/>

<input type="button" value="登录" class="button" onclick="AjaxRequst()">

</form>

</body>

</html>

login.php

<?php

header("Content-type:text/html;charset=utf-8");

if($_POST['username']=='php'&& $_POST['password']=='123')

{

echo ("hello");

}else{

echo ("用户名或密码错误");

}

?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: