Home > Web Front-end > HTML Tutorial > Ajax in brief_html/css_WEB-ITnose

Ajax in brief_html/css_WEB-ITnose

WBOY
Release: 2016-06-24 11:53:37
Original
883 people have browsed it

You must be familiar with Ajax, but do you really want to talk about what it is? It is estimated that not many people have given a complete definition.

The specific definition of Ajax from W3C is:

AJAX = Asynchronous JavaScript and XML (asynchronous JavaScript and XML).

In other words, AJAX is the art of exchanging data with the server and updating parts of the web page without reloading the entire page.

AJAX is a technology for creating fast, dynamic web pages.

AJAX allows web pages to be updated asynchronously by exchanging a small amount of data with the server in the background. This means that parts of a web page can be updated without reloading the entire page.

Traditional web pages (not using AJAX) must reload the entire web page if the content needs to be updated.

Of course we must have a basic understanding of the following knowledge before learning Ajax:

  • HTML / XHTML
  • CSS
  • JavaScript / DOM
  • XMLHttpRequest is the basis of AJAX.

    All modern browsers support the XMLHttpRequest object (IE5 and IE6 use ActiveXObject). All modern browsers (IE7, Firefox, Chrome, Safari and Opera) have built-in XMLHttpRequest objects.

    XMLHttpRequest is used to exchange data with the server in the background. This means that parts of a web page can be updated without reloading the entire page.

    The specific code to create XMLHttpRequest is as follows:

    //为了应对所有的现代浏览器,包括 IE5 和 IE6,请检查浏览器是否支持 XMLHttpRequest 对象。如果支持,则创建 XMLHttpRequest 对象。如果不支持,则创建 ActiveXObject var xmlhttp;if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari    xmlhttp = new XMLHttpRequest();}else {// code for IE6, IE5  老版本的 Internet Explorer (IE5 和 IE6)使用 ActiveX 对象    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");}
    Copy after login

    Before introducing the XMLHttpRequest object for exchanging data with the server, let’s briefly understand it Let’s take a look at the pros and cons of the get and post methods to facilitate choosing a more suitable request method during subsequent development.

    Compared to POST, GET is simpler and faster, and works in most cases.

    However, use POST requests in the following situations:

  • Cache files cannot be used (updating files or databases on the server)
  • Sending large amounts of data to the server (POST There is no limit on the amount of data)
  • When sending user input containing unknown characters, POST is more stable and reliable than GET
  • XMLHttpRequest exchanges data with the server mainly through the open and send methods, where if If the get method is used in the open method, then the send method does not need to pass any parameters. If the post method is used, then what is passed in the send method is a string similar to querystring.

    The following is a brief introduction to several main methods:

    Method Description
    open(method,url,async)
    方法 描述
    open(method,url,async)

    规定请求的类型、URL 以及是否异步处理请求。

  • method:请求的类型;GET 或 POST
  • url:文件在服务器上的位置
  • async:true(异步)或 false(同步)
  • send(string)

    将请求发送到服务器。

  • string:仅用于 POST 请求
  • setRequestHeader(header,value)

    向请求添加 HTTP 头。

  • header: 规定头的名称
  • value: 规定头的值
  • Specifies the type of request, URL and whether to process the request asynchronously. <🎜> <🎜>method: type of request; GET or POST <🎜> <🎜>url: location of the file on the server <🎜> <🎜>async: true (asynchronous) or false (synchronous) <🎜> < /td>
    send(string) <🎜>Sends the request to the server. <🎜> <🎜>string: only used for POST requests <🎜>
    setRequestHeader(header,value) <🎜>Add HTTP to the request head. <🎜> <🎜>header: specifies the name of the header <🎜> <🎜>value: specifies the value of the header <🎜>

    事实上,open方法中的async参数如果设计为false的话,那么发送的请求则跟传统的方式没有区别,也就是说必须等待服务器端数据回来之后才能接着进行下步操作。javaScript 会等到服务器响应就绪才继续执行。如果服务器繁忙或缓慢,应用程序会挂起或停止。所以我们不推荐使用 async=false。

    当您使用 async=false 时,请不要编写 onreadystatechange 函数 - 把代码放到 send() 语句后面即可:

    xmlhttp.open("GET", "test1.txt", false);xmlhttp.send();document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
    Copy after login

    当使用 async=true 时,请规定在响应处于 onreadystatechange 事件中的就绪状态时执行的函数:

    xmlhttp.onreadystatechange = function () {    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {        document.getElementById("myDiv").innerHTML = xmlhttp.responseText;    }}xmlhttp.open("GET", "test1.txt", true);xmlhttp.send();
    Copy after login

    大家注意当使用async=true 时,它的返回值当中有两个重要的属性,那便是responseText 和responseXML 。其中responseText 获得字符串形式的响应数据而responseXML 获得 XML 形式的响应数据。如果来自服务器的响应并非 XML,请使用 responseText 属性。如果来自服务器的响应是 XML,而且需要作为 XML 对象进行解析,请使用 responseXML 属性。

    在 onreadystatechange 事件中,我们规定当服务器响应已做好被处理的准备时所执行的任务。

    当 readyState 等于 4 且状态为 200 时,表示响应已就绪

    当请求被发送到服务器时,我们需要执行一些基于响应的任务。

    每当 readyState 改变时,就会触发 onreadystatechange 事件。

    readyState 属性存有 XMLHttpRequest 的状态信息。

    下面是 XMLHttpRequest 对象的三个重要的属性:

    属性 描述
    onreadystatechange 存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。
    readyState

    存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。

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

    200: "OK"

    404: 未找到页面

    下面以一个简单的demo温习一下上述介绍的基础知识

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head>    <title></title>    <script type="text/javascript">        var xmlhttp;        function loadXMLDoc(url) {            xmlhttp = null;            if (window.XMLHttpRequest) {// code for Firefox, Opera, IE7, etc.                xmlhttp = new XMLHttpRequest();            }            else if (window.ActiveXObject) {// code for IE6, IE5                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.");            }        }        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('example/ajax/test_xmlhttp.txt')">    <div id="T1" style="border: 1px solid black; height: 40px; width: 300px; padding: 5px">    </div>    <br />    <button onclick="loadXMLDoc('example/ajax/test_xmlhttp2.txt')">        Click</button></body></html>
    Copy after login

     

    Related labels:
    source:php.cn
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template