zoukankan      html  css  js  c++  java
  • AJAX请求相关知识

    一. AJAX简介

    1. 什么是AJAX
      AJAX=异步JavaScript和XML,是一种用于创建快速动态网页的技术.
      AJAX通过在后台与服务器进行少量数据交互,可以使网页实现异步更新,即可以让网页在不重新加载整个页面的情况下,值对某些部分进行更新.
    2. AJAX工作原理
      ALT

    二. AJAX实例

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <script>
    function loadXMLDoc()
    {
    	var xmlhttp;
    	if (window.XMLHttpRequest)
    	{
    		//  IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
    		xmlhttp=new XMLHttpRequest();
    	}
    	else
    	{
    		// IE6, IE5 浏览器执行代码
    		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    	}
    	xmlhttp.onreadystatechange=function()
    	{
    		if (xmlhttp.readyState==4 && xmlhttp.status==200)
    		{
    			document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    		}
    	}
    	xmlhttp.open("GET","/try/ajax/ajax_info.txt",true);
    	xmlhttp.send();
    }
    </script>
    </head>
    <body>
    <div id="myDiv"><h2>使用 AJAX 修改该文本内容</h2></div>
    <button type="button" onclick="loadXMLDoc()">修改内容</button>
    </body>
    </html>
    

    三. AJAX-创建XMLHttpRequest对象

    XMLHttpRequest对象用于在后台与服务器交换数据.可以在不重新加载整个网页的情况下,对网页的某部分进行更新.

    • 创建XMLHttpRequest对象
      创建XMLHttpResquest语法:
    variable=new XMLHttpRequest();
    
    实例:
    var xmlhttp;
    if (window.XMLHttpRequest)
    {
    // IE7+,Firefox,Chrome,Opera,Safari浏览器执行代码
    xmlhttp=new XMLHttpRequest();
    }
    else
    {
    // IE6,IE5浏览器执行代码
    xmlhttp=new ActiveXobject("Microsoft.XMLHTTP")
    }
    

    四. AJAX-向服务器发送请求

    1. 向服务器发送请求
      可以使用XMLHttpRequest对象的open()和send()方法来将请求发送到服务器

      • xmlhttp.open("GET","ajax_info.txt",true);
        open(method,url,async) :规定请求的类型、URL 以及是否异步处理请求。
        method:请求的类型;GET 或 POSTurl:文件在服务器上的位置async:true(异步)或 false(同步)
      • xmlhttp.send();
        send(string) 将请求发送到服务器。string:仅用于 POST 请求
    2. GET和POST方法
      一般情况下,get和post方法都可以用,在以下情况,使用post请求:

      • 无法使用缓存文件(更新服务器上的文件或数据库)
      • 向服务器发送大量数据(POST 没有数据量限制)
      • 发送包含未知字符的用户输入时,POST 比 GET 更稳定也更可靠

      GET请求

    实例:
    xmlhttp.open("GET","/try/ajax/demo_get.php?t="+Math.random(),true);
    xmlhttp.send();
    
    **POST请求**
    
    实例:
    xmlhttp.open("POST","/try/ajax/demo_post2.php",true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send("fname=Henry&lname=Ford");
    
    1. url-服务器上的文件
      open() 方法的 url 参数是服务器上文件的地址:
    xmlhttp.open("GET","ajax_test.html",true);
    
    该文件可以是任何类型的文件,比如 .txt 和 .xml,或者服务器脚本文件,比如 .asp 和 .php (在传回响应之前,能够在服务器上执行任务)。  
    XMLHttpRequest 对象如果要用于 AJAX 的话,其 open() 方法的 async 参数必须设置为 true.
    

    五. AJAX-服务器响应

    可以使用XMLHttpRequest对象的responseText或responseXML属性来获得来自服务器的响应.

    • responseText属性
      如果来自服务器的响应并非 XML,请使用 responseText 属性。
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    
    • responseXML属性
      如果来自服务器的响应是 XML,而且需要作为 XML 对象进行解析,请使用 responseXML 属性:
    xmlDoc=xmlhttp.responseXML;
    txt="";
    x=xmlDoc.getElementsByTagName("ARTIST");
    for (i=0;i<x.length;i++)
    {
        txt=txt + x[i].childNodes[0].nodeValue + "<br>";
    }
    document.getElementById("myDiv").innerHTML=txt;
    

    六. AJAX-onreadystatechange事件

    1. onreadystatechange事件
      当请求被发送到服务器时,每当readyState改变时,就会触发onreadystatechange事件.
      在 onreadystatechange 事件中,我们规定当服务器响应已做好被处理的准备时所执行的任务。
      当 readyState 等于 4 且状态为 200 时,表示响应已就绪:
    实例
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
        }
    }
    
    1. 使用回调函数
      回调函数是一种以参数形式传递给另一个函数的函数
    实例
    function myFunction()
    {
        loadXMLDoc("/try/ajax/ajax_info.txt",function()
        {
            if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
                document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
            }
        });
    }
    

    七. 更多实例

    例子中的公共函数部分:

    var xmlhttp;
    function loadXMLDoc(url)
    {
    	xmlhttp=null;
    	if (window.XMLHttpRequest)
    	{
    		xmlhttp=new XMLHttpRequest();
    	}
    	else if(window.ActiveXobject)
    	{
    		xmlhttp=new ActiveXobject("Microsoft.XMLHTTP");
    	}
    	if (xmlhttp!=null)
    	{
    		xmlhttp.onreadystatechange=state\_Change;
    		xmlhttp.open("GET",url,true);
    		xmlhttp.send(null);
    	}
    	else
    	{
    		alert("your browser does not support XMLHTTP.");
    	}
    }
    
    1. 通过XMLHTTP把文本文件载入HTML元素
    <!DOCTYPE html>
    <html>
    <head>
    <script type="text/javascript">
           ........         // 公共函数
    	function state_Change()
    	{
    		if (xmlhttp.readyState==4)
    		{
    			// 4="loaded"
    			if (xmlhttp.status==200)
    			{
    				//200="OK"
    				document.getElementById('T1').innerHTML=xmlhttp.responseText;
    			}
    			else{
    				alert("Problem retrieving data:"+xmlhttp.statusText);
    			}
    		}
    	}
    </script>
    </head>
    <body onload="loadXMLDoc('test\_xmlhttp.txt')">
    <div id="T1"style="border:1px solid black;height:200;300;padding:5"></div><br />
    <button onclick="loadXMLDoc('test\_xmlhttp1.txt')">Click</button>
    </body>
    </html>
    

    ALT
    2. 通过XMLHTTP加载XML文件

    <html>
    <head>
    <script type="text/javascript">
    	...........      //公共函数部分
    	function state_Change()
    	{
    		if (xmlhttp.readyState==4)
    		{
    			// 4="loaded"
    			if (xmlhttp.status==200)
    			{
    				//200="OK"
    				document.getElementById("A1").innerHTML=xmlhttp.status;
    				document.getElementById("A2").innerHTML=xmlhttp.statusText;
    				document.getElementById("A3").innerHTML=xmlhttp.responseText;
    			}
    			else{
    				alert("Problem retrieving data:"+xmlhttp.statusText);
    			}
    		}
    	}
    </script>
    </head>
    <body>
    	<h2>using the httpresquest boject</h2>
    	<p>
    		<b>status:</b>
    		<span id="A1"></span>
    	</p>
    	<p>
    		<b>status text:</b>
    		<span id="A2"></span>
    	</p>
    	<p>
    		<b>response:</b>
    		<span id="A3"></span>
    	</p>
    	<button onclick="loadXMLDoc('test.html')">get xml</button>
    </body>
    </html>
    

    ALT
    3. 通过XMLHTTP进行一次HEAD请求

    <html>
    <head>
    <script type="text/javascript">
    	...........   //公共函数部分
    	function state_Change()
    	{
    		if (xmlhttp.readyState==4)
    		{
    			// 4="loaded"
    			if (xmlhttp.status==200)
    			{
    				//200="OK"
    				document.getElementById('p1').innerHTML=xmlhttp.getAllResponseHeaders();
    			}
    			else{
    				alert("Problem retrieving data:"+xmlhttp.statusText);
    			}
    		}
    	}
    </script>
    </head>
    <body>
    	<p id="p1">
    	The getAllResponseHeaders() function returns the headers of a resource.
    	The headers contain file information like length,
    	server-type, content-type, date-modified, etc.
    	</p>
    	<button onclick="loadXMLDoc('test2.html')">get headers</button>
    </body>
    </html>
    

    ALT

  • 相关阅读:
    常用cmd命令总结
    百度地图api的简单应用(二):轻量级路径规划
    百度地图api的简单应用(一):POI检索
    R语言-八皇后问题
    8086基本IO口的仿真
    输入输出与中断
    汇编语言例子
    变量标号
    变量声明
    串操作指令2
  • 原文地址:https://www.cnblogs.com/magicianyin/p/8529303.html
Copyright © 2011-2022 走看看