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

Ajax in brief_html/css_WEB-ITnose

Jun 24, 2016 am 11:53 AM

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

     

    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

    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

    Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Nordhold: Fusion System, Explained
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Hot Topics

    Java Tutorial
    1667
    14
    PHP Tutorial
    1273
    29
    C# Tutorial
    1255
    24
    HTML: The Structure, CSS: The Style, JavaScript: The Behavior HTML: The Structure, CSS: The Style, JavaScript: The Behavior Apr 18, 2025 am 12:09 AM

    The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

    The Future of HTML, CSS, and JavaScript: Web Development Trends The Future of HTML, CSS, and JavaScript: Web Development Trends Apr 19, 2025 am 12:02 AM

    The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

    The Future of HTML: Evolution and Trends in Web Design The Future of HTML: Evolution and Trends in Web Design Apr 17, 2025 am 12:12 AM

    The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

    HTML vs. CSS vs. JavaScript: A Comparative Overview HTML vs. CSS vs. JavaScript: A Comparative Overview Apr 16, 2025 am 12:04 AM

    The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

    HTML: Building the Structure of Web Pages HTML: Building the Structure of Web Pages Apr 14, 2025 am 12:14 AM

    HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

    HTML vs. CSS and JavaScript: Comparing Web Technologies HTML vs. CSS and JavaScript: Comparing Web Technologies Apr 23, 2025 am 12:05 AM

    HTML, CSS and JavaScript are the core technologies for building modern web pages: 1. HTML defines the web page structure, 2. CSS is responsible for the appearance of the web page, 3. JavaScript provides web page dynamics and interactivity, and they work together to create a website with a good user experience.

    HTML: Is It a Programming Language or Something Else? HTML: Is It a Programming Language or Something Else? Apr 15, 2025 am 12:13 AM

    HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

    From Text to Websites: The Power of HTML From Text to Websites: The Power of HTML Apr 13, 2025 am 12:07 AM

    HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

    See all articles