目录结构:

contents structure [+]

Ajax是Asynchronous JavaScript and XML(异步的JavaScript和XML)的简介,Ajax并不是一门新的编程语言,而是一种使用现有标准的新方法。它能够在不重新加载整个页面的情况下,可以与服务器交换数据并更新部分网页内容。

2,Ajax工作原理

【JavaScript】浅析ajax的使用

通过这个原理图,我们可以看出我们写的javascript代码首先会经过ajax引擎,由ajax引擎负责和server进行通信,再将通信的结果返回给浏览器。这样就不需要刷新整个网页,从而实现向服务器请求数据。

3,Ajax的使用步骤

3.1,使用原生js

1.创建XMLHttpRequest对象

所有现代的浏览器都内建了XMLHttpRequest对象,创建的语法为: var xmlhttp=new XMLHttpRequest();

老版本的IE5,IE6使用ActiveX对象,语法为: var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 。

2.传入回调函数onreadystatechange

xmlhttp.onreadystatechange=function(){
    if(xmlhttp.readyState==4 && xmlhttp.status==200){
         //document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
        }
} 

readState的状态码:

  • 0: 请求未初始化
  • 1: 服务器连接已建立
  • 2: 请求已接收
  • 3: 请求处理中
  • 4: 请求已完成,且响应已就绪

status的状态码:

  • 200: 请求成功
  • 302:请求重定向
  • 404: 资源未找到
  • 500:服务器错误

3.向服务器发送请求

xmlhttp.open(Method,URL,async);
xmlhttp.send();

这里涉及到参数的问题,如果是使用POST请求提交参数,那么参数需要在send()方法中传入,如果使用GET请求提交参数,那么参数需要拼接到URL后面。

4.案例

html文件:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户登录</title>
<script type="text/javascript">
function userSubmit(){
    //创建对象
    var xmlhttp;
    if(window.XMLHttpRequest){
        xmlhttp = new XMLHttpRequest();
    }else{
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    //传入回调函数onreadystatechange
    xmlhttp.onreadystatechange=function(){
        if(xmlhttp.readyState==4 && xmlhttp.status==200){//请求成功
            document.getElementById("logininfo").innerHTML=xmlhttp.responseText;
        }
    }
    //发送请求
    xmlhttp.open("POST","login.do",true);
    //如果希望通过POST传输数据,那么应该先通过setRequestHeader()添加Http头数据
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    var unamevalue=document.getElementById("unameid").value;
    var upassvalue=document.getElementById("upassid").value;
    xmlhttp.send("uname="+unamevalue+"&upass="+upassvalue);
}
</script>
</head>
<body>
<div>
请输入用户名:<input type="text" /><p><p>
请输入密码:<input type="password" /><p><p>
<input type="button" value="点击我" onclick="userSubmit()"/><p><P>
<span ></span>
</div>
</body>
</html>
login.html

相关文章:

  • 2021-12-08
  • 2021-06-30
  • 2021-09-12
  • 2021-09-09
  • 2021-06-26
  • 2021-09-15
猜你喜欢
  • 2022-12-23
  • 2021-10-14
  • 2021-12-24
  • 2021-12-24
  • 2022-12-23
  • 1970-01-01
  • 2021-10-10
相关资源
相似解决方案