search
HomeWeb Front-endHTML TutorialAjax in brief_html/css_WEB-ITnose

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");}

    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)
    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;

     

    当使用 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();

    大家注意当使用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>

     

    Statement
    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
    The Future of HTML: Evolution and TrendsThe Future of HTML: Evolution and TrendsMay 13, 2025 am 12:01 AM

    The future of HTML will develop in a more semantic, functional and modular direction. 1) Semanticization will make the tag describe the content more clearly, improving SEO and barrier-free access. 2) Functionalization will introduce new elements and attributes to meet user needs. 3) Modularity will support component development and improve code reusability.

    Why are HTML attributes important for web development?Why are HTML attributes important for web development?May 12, 2025 am 12:01 AM

    HTMLattributesarecrucialinwebdevelopmentforcontrollingbehavior,appearance,andfunctionality.Theyenhanceinteractivity,accessibility,andSEO.Forexample,thesrcattributeintagsimpactsSEO,whileonclickintagsaddsinteractivity.Touseattributeseffectively:1)Usese

    What is the purpose of the alt attribute? Why is it important?What is the purpose of the alt attribute? Why is it important?May 11, 2025 am 12:01 AM

    The alt attribute is an important part of the tag in HTML and is used to provide alternative text for images. 1. When the image cannot be loaded, the text in the alt attribute will be displayed to improve the user experience. 2. Screen readers use the alt attribute to help visually impaired users understand the content of the picture. 3. Search engines index text in the alt attribute to improve the SEO ranking of web pages.

    HTML, CSS, and JavaScript: Examples and Practical ApplicationsHTML, CSS, and JavaScript: Examples and Practical ApplicationsMay 09, 2025 am 12:01 AM

    The roles of HTML, CSS and JavaScript in web development are: 1. HTML is used to build web page structure; 2. CSS is used to beautify the appearance of web pages; 3. JavaScript is used to achieve dynamic interaction. Through tags, styles and scripts, these three together build the core functions of modern web pages.

    How do you set the lang attribute on the  tag? Why is this important?How do you set the lang attribute on the tag? Why is this important?May 08, 2025 am 12:03 AM

    Setting the lang attributes of a tag is a key step in optimizing web accessibility and SEO. 1) Set the lang attribute in the tag, such as. 2) In multilingual content, set lang attributes for different language parts, such as. 3) Use language codes that comply with ISO639-1 standards, such as "en", "fr", "zh", etc. Correctly setting the lang attribute can improve the accessibility of web pages and search engine rankings.

    What is the purpose of HTML attributes?What is the purpose of HTML attributes?May 07, 2025 am 12:01 AM

    HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform

    How do you create a list in HTML?How do you create a list in HTML?May 06, 2025 am 12:01 AM

    TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.

    HTML in Action: Examples of Website StructureHTML in Action: Examples of Website StructureMay 05, 2025 am 12:03 AM

    HTML is used to build websites with clear structure. 1) Use tags such as, and define the website structure. 2) Examples show the structure of blogs and e-commerce websites. 3) Avoid common mistakes such as incorrect label nesting. 4) Optimize performance by reducing HTTP requests and using semantic tags.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Article

    Hot Tools

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    SecLists

    SecLists

    SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

    Dreamweaver Mac version

    Dreamweaver Mac version

    Visual web development tools