Scripting HTTP with Ajax
The main feature of AJax is to use scripts to manipulate data exchange between HTTP and web servers without causing page reloading.
Using XMLHttpRequest
All modern browsers support the XMLHttpRequest object (IE5 and IE6 use ActiveXObject).
Create XMLHttpRequest object
var xmlhttp =new XMLHttpRequest()
var xmlhttp =new ActiveXObject("Microsoft.XMLHTTP");
For example
function createXML(){ if(typeof XMLHttpRequest != "undefined"){//标准 return new XMLHttpRequest(); }else if(typeof ActiveXObject != "undefined"){//兼容IE5,IE6 if(typeof arguments.callee.activeXString != "string"){ var versions = ["MSXML2.XMLHttp.6.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp"],i,len; for (i=0,len=versions.length; i < len; i++) { try{ new ActiveXObject(versions[i]); arguments.callee.activeXString = versions[i]; break; }catch(ex){ //跳过 } } } return new ActiveXObject(arguments.callee.activeXString); }else{ throw new Error("no XRL object available."); } }var xml = new createXML();
Specify request
After the object is created, the next step to initiate an http request is to call the open() method of the XMLHttpRequest object. It receives three parameters:
The type of request to send, case-insensitive
The requested URL, here relative to the document URL, if the absolute URL, protocol, host and port are specified, they must match the corresponding content of the document: cross-domain requests will usually report an error
Boolean value of whether to send asynchronously;
If there is request header, then the next step is to set it.
xml.setRequestHeader("Content-Type","text/plain");
If the request header is called multiple times, overwriting will not occur
If the request requires a password-protected URL, the username and The password is passed as the fourth and fifth parameters to open()
The last step in making the request is to specify the optional body and send it to the server. It should be noted that GET requests have absolutely no body, but when using POST to send a request, you must cooperate with the setRequestHeader method
xml.send(null);
Get a response
A complete HTTP response has a status code, response It consists of a collection of headers and a response body. These are available through the properties and methods of the XMLHttpRequest object:
- The status and statusText properties return the HTTP status code (such as 200 ok) in the form of numbers and text
- Use getResponseHeader and getAllResponseHeaders() to query response headers
- The response body can be obtained in text form from the responseText attribute and in Document form from the responseXML attribute
- XMLHttpRequest objects are typically used asynchronously: the send method returns immediately after sending the request, and the response methods and properties listed previously are not valid until the response returns. In order to be notified when the response is ready, you must listen to the readystatechange event on the XMLHttp object
readyState is an integer that specifies the status of the HTTP request
For example
var xml = new createXML();xml.open("get","hello-world.html",false);xml.onreadystatechange = function(url,callback){ if(xml.readyState === 4){ if((xml.status >= 200 && xml.status < 300) || xml.status === 304){ console.log(xml.responseText); }else{ console.log("request is not ok" + xml.status); } } }xml.send(null);
Console output
Meaning | ||
---|---|---|
Content type that the browser can handle | ||
Character set that can be displayed | ||
Compression encoding that can be processed | ||
Between browser and server The connection type | ||
The domain where the page is located | ||
The cookie set by the page | ||
The page URL from which the request was made | ||
Browser User Agent String |
事件 | 事件处理程序 | 描述 |
---|---|---|
open | Socket.onopen | 连接建立时触发 |
message | Socket.onmessage | 客户端接收服务端数据时触发 |
error | Socket.onerror | 通信发生错误时触发 |
close | Socket.onclose | 连接关闭时触发 |
参考文档——websocket
AJax的主要特点是使用脚本操纵HTTP和web服务器之间的数据交换,不会导致页面重载。
The above is the detailed content of Scripting HTTP with Ajax. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

Understand the meaning of HTTP 301 status code: common application scenarios of web page redirection. With the rapid development of the Internet, people's requirements for web page interaction are becoming higher and higher. In the field of web design, web page redirection is a common and important technology, implemented through the HTTP 301 status code. This article will explore the meaning of HTTP 301 status code and common application scenarios in web page redirection. HTTP301 status code refers to permanent redirect (PermanentRedirect). When the server receives the client's

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

The HTTP request times out, and the server often returns the 504GatewayTimeout status code. This status code indicates that when the server executes a request, it still fails to obtain the resources required for the request or complete the processing of the request after a period of time. It is a status code of the 5xx series, which indicates that the server has encountered a temporary problem or overload, resulting in the inability to correctly handle the client's request. In the HTTP protocol, various status codes have specific meanings and uses, and the 504 status code is used to indicate request timeout issues. in customer

As a world-renowned short video social platform, Douyin has won the favor of a large number of users with its unique personalized recommendation algorithm. This article will delve into the value and principles of Douyin video recommendation to help readers better understand and make full use of this feature. 1. What is Douyin recommended video? Douyin recommended video uses intelligent recommendation algorithms to filter and push personalized video content to users based on their interests and behavioral habits. The Douyin platform analyzes users' viewing history, like and comment behavior, sharing records and other data to select and recommend videos that best suit users' tastes from a huge video library. This personalized recommendation system not only improves user experience, but also helps users discover more video content that matches their preferences, thereby enhancing user stickiness and retention rate. at this
