Home >Web Front-end >JS Tutorial >How to write ajax in js
Using ajax in JavaScript has two functions:
1. Let js read the data on the server.
2. No refresh Under certain circumstances, read the data on the server, for example: verify whether the account and password are correct, etc.
We know that there are two types of network requests: Get and Post. What is the difference between them?
Get method: Common form submission method: submit the value after the url;?name=value&name=value format.
Submit form example:
<form action="www.baidu.com " method="get" (默认是get方式)> 姓名:<input type="text" name="userName"></br> 密码:<input type="password" name="password"> <input type="submit" value="提交"> </from>
Difference:
1. The get method transmits data through the URL, and the post method transmits data through the Content in http.
2. The get capacity is small and is not suitable for transmission For big data, (generally 4k-10k), the capacity of the post mode is relatively large. Generally, the server can reach 2G capacity.
3. For files that are too large, post will not be used, but the control will be used.
4. The get method has poor security, and post is relatively better. For those who are safe, you can only use https.
5. The get method has a cache, but the post does not. Get is more suitable for sending messages to the server To obtain data, post is more suitable for transmitting data to the server.
There are two ways to write AJAX in JS:
GET method:
var ajaxObj=new XMLHttpRequest(); ajaxObj.open("GET","../php/ajaxSubmitData.php?data=tody is wind"); ajaxObj.send() ajaxObj.onreadystatechange= function () { if(ajaxObj.readyState===4&&ajaxObj.status){ alert("发送成功"); } }
POST method:
var ajaxObj=new XMLHttpRequest(); ajaxObj.open("POST","../PHP/ajaxSubmitData.php"); ajaxObj.setRequestHeader("Content-type","application/x-www-form-urlencoded"); // multipart/form-data 默认的以二进制方式传送 ajaxObj.send("data=我是post数据"); ajaxObj.onreadystatechange= function () if(ajaxObj.readyState===4&&ajaxObj.status===200){ alert("发送数据成功"); } }
ajax gets the data returned from the server by ajaxObj.responseText
ajax sends data to the server: get post
get: url rewriting (splicing) ---- small amount of data, simple data is not safe
post:send(data) request body (cannot be seen on the page) large amount of data, simple or complex Data security
application/x-www-form-urlencoded means that the form is sent in the form of a string by default
multipart/form-data The form data is sent in the form of a binary stream
ajaxObj.setRequestHeader actually modifies the Content-type value in the request header (request message)
The above is the detailed content of How to write ajax in js. For more information, please follow other related articles on the PHP Chinese website!