Introduction and use of AJAX
What is ajax
- AJAX is a technology that can follow new parts of a web page without reloading the entire web page.
- AJAX=AJAX = Asynchronous JavaScript and XML( 异步 javascript和XML)
Create an XMLHttpRequest object
- The XMLHttpRequest object is used to exchange data with the server.
grammar:
var str = new XMLHttpRequest();
Send a request to the server
- To send a request to the server, we use the open() and send() methods of the XMLHttpRequest object:
// method:请求的类型;GET 或 POST
// url:文件在服务器上的位置
// async:true(异步)或 false(同步) ,默认值true,可选参数.
str.oppn(method,url,async);
str.send();
get request method
//1.创建一个xmlhttpRequset对象
var xhr = new XMLHttpRequest();
// 2.调用open方法
//open方法有三个参数:
// 1.请求的方式 method get/post
// 2.请求的url
// 3.是否异步,默认值true,可选参数.
str.open("get", "http://localhost/data.php?id=1");
//3.调用send方法
xhr.send();
//4.监听状态的改变。
xhr.onreadystatechange = function () {
}
post request
//1.创建一个xmlhttpRequset对象
var xhr = new XMLHttpRequest();
// 2.调用open方法
//open方法有三个参数:
// 1.请求的方式 method get/post
// 2.请求的url
// 3.是否异步,默认值true,可选参数.
xhr.open("post", "http://localhost/post.php");
//3.调用send方法
//post请求需要设置请求头。
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
xhr.send("id=2");
//4.监听状态的改变。
xhr.onreadystatechange = function () {
}
Server response
- To get the response from the server, use the responseText or responseXML property of the XMLHttpRequest object.
responseText property
The responseText property returns the response as a string
responseXML attribute
- If the response from the server is XML and needs to be parsed as an XML object