In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article introduces the relevant knowledge of "how to interact with ajax". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Synchronous and asynchronous
Synchronization: it means doing one thing at a time. Wait until the previous task is done before you can do the latter task.
Asynchronous: not affected by the current task, two things are done at the same time, and when you do one thing, it does not affect the progress of the other.
Programming: asynchronous program code execution will not block the execution of other program code, so as to improve the overall execution efficiency.
The concept of ajax what is ajax
1 Ajax: asynchronous javascript and xml (Asynchronous js and xml)
2 is one of the technologies that can interact (asynchronously / synchronously) with the server.
The language carrier of ajax is javascript. The most important feature: some common applications of ajax without page refresh, so that the web page does not refresh to send request data to the web server.
The history of ajax appearance
In 1999, Microsoft released the IE5 browser as an embedded technology. Originally, the name was XMLHttp.
Until 2005, google released a mailbox product, gmail, which uses ajax technology internally, which drew people's attention to ajax and made people pay attention to the depressed javascript language.
Using XMLHttpRequest objects for ajax
The browser has built-in objects for communicating with the server (exchanging data) so that we can partially update the web page instead of refreshing the entire page. This request is asynchronous, that is, when the request is sent to the server, it will not hinder the running of the program, and the browser will continue to render the subsequent structure.
Operation of ajax
Be sure to open the phpsudy,js file and the php file on the same host before the request is successful.
Creation and sending of creation request for GET request
The creation of mainstream browsers (Firefox, google, Apple safari, opera, including versions above IE8) is also mainly used now.
/ / 1. Create a XMLHttpRequest object var xhr = new XMLHttpRequest (); / / 2. Set the type of request, and address / / first parameter: request method get/post// second parameter: request address needs to be spelled with parameter list after url / / third parameter: default is asynchronous xhr.open ("get", "01.php?name=Jepson", asynchronous / synchronous); / / 3. Send a request to the server xhr.send (null)
Manual location
Http://www.w3school.com.cn/ajax/ajax_xmlhttprequest_create.asp
The use of GET
Example 1: add a button to the page, click to send a request to the php backend at a time, and php writes a paragraph of text to a.txt
Summary:
1 create object let xhr = new XMLHttpRequest (); 2 set request xhr.open (get, request address) 3 send request xhr.send () 4 determine status to receive return value xhr.onreadystatechange = funtion () {if (xhr.readyState==4 & & xhr.status==200) {/ / accept return value let str = xhr.response}} get and post
1 get is accessed through the address bar and is visible
(2) the amount of data transferred by get is relatively small. The security is low.
3 post is accessed in the form of non-address bar, which is secure and can pass through a large amount of data.
Common use of post
Used in forms, used in ajax
POST request step
Create an Ajax object.
Sets the callback function. Receive the result returned by the backend
Set up request
Set request header information "Content-type,application/x-www-form-urlencoded"
Send a request.
Fulfill the request
SetRequestHeader () sets request header information
Application/x-www-form-urlencoded sets the encoding format used when passing parameters (default)
Example: transfer data in post way
Function F1 () {/ / instantiate the ajax object var xhr = new XMLHttpRequest (); / / set the parameters of the request, set the request xhr.open ('post','./post.php') in post mode; / / if you need POST data like the HTML form, transfer the data xhr.setRequestHeader in the form of & (' content-type', 'application/x-www-form-urlencoded') / / construct the passed parameters in the same way as get passes parameters var data = 'name= Zhang San & age=19'; / / send request xhr.send (data) / / accept the returned information xhr.onreadystatechange=function () {/ / verify the current configuration accept the returned information if (xhr.readyState==4) {/ / accept the letter returned by the server var info = xhr.responseText; alert (info) } function fn () {/ / 1 instantiate object let xhr = new XMLHttpRequest (); / / get the four states of ajax xhr.onreadystatechange = function (state) {/ / console.log (xhr.readyState) / / alert (xhr.responseText) if (xhr.readyState==4) {console.log (xhr.response)} / / 2 set the type and address of the request. The third parameter is set to false, indicating synchronization, and set to true to indicate asynchronous (default) xhr.open ('get',' http://localhost/demo.php',). False) / / 3 send a request, the get request is set to null, and the post request sets the parameter xhr.send (); / / verify the console.log (11111) that must be written for synchronization;} / / console.log (eval ('{}')); / / console.log (eval ('({})'))
PHP code
When testing a synchronization request, the responseText that gets the returned result must be placed before send ()
Service returns data format processing type
Text (also known as HTML format)
XML format
JSON format
Text type handles var xhr = new XMLHttpRequest (); xhr.onreadystatechange = function () {if (xhr.readyState==4) {/ / accept the returned message var info = xhr.responseText; alert (info);}} xhr.open ('get','./geshi.php'); xhr.send (null) [php code] echo'it's over, it's almost over!'; processing of json data
Use JOSN.parse () to convert the json string output from PHP to an object
Var xhr = new XMLHttpRequest (); xhr.onreadystatechange = function () {if (xhr.readyState==4) {/ / accept the returned message, var info = xhr.responseText; / / convert the json array to a js object var str = JSON.parse (info); console.log (str) }} xhr.open ('get','./geshi.php'); xhr.send (null); [PHP Code] echo json_encode (array ("name" = >' Zhang San', "age" = >'12')); processing of xml data var xhr = new XMLHttpRequest () Xhr.onreadystatechange = function () {if (xhr.readyState==4) {/ / accept the returned message and use responseXML to accept var info = xhr.responseXML; var msg=info.getElementsByTagName ('msg') [0] [xss_clean]; console.log (msg) }} xhr.open ('get','./geshi.php'); xhr.send (null); [PHP Code] {return new Promise (function (resolve,reject) {let xhr = new XMLHttpRequest (); xhr.open (' get',param.url); / / default is true, indicating asynchronous xhr.send () Xhr.onreadystatechange = function () {if (xhr.readyState==4) {if (xhr.status==200) {resolve (xhr.responseText)} else {reject (xhr.responseText)} }) }
Step 2: use then and catch to get the result
AjaxPromise ({type:'get',url:'http//:www.baidu.com',data:null}) .then (function (data) {}) .catch (function (data) {}); extension: Promise.all ()
A method that executes after all asynchronous requests are completed.
Promse.all is very useful when dealing with multiple asynchronous processes, for example, a page needs to wait for the data of two or more ajax to be displayed properly, and before that, only the loading icon is displayed.
Let wake = (time) = > {return new Promise ((resolve, reject) = > {setTimeout (()) = > {resolve (`${time / 1000} seconds to wake up)}, time)})} let p1 = wake (3000); let p2 = wake (2000) Promise.all ([p1, p2]) .then ((result) = > {console.log (result) / ['wake up in 3 seconds', 'wake up in 2 seconds']}) .catch ((error) = > {console.log (error)}) will execute allPromise.race () only after two calls to promise have been completed.
Promse.race means a race, which means that any result in Promise.race ([p1, p2, p3]) will be returned to that result, regardless of whether the result itself is successful or failed.
Let p1 = new Promise ((resolve, reject) = > {setTimeout (() = > {resolve ('success')}, 1000)}) let p2 = new Promise ((resolve, reject) = > {setTimeout (() = > {reject (' failed')}, 500)}) Promise.race ([p1) P2]) .then ((result) = > {console.log (result)}) .catch ((error) = > {console.log (error) / / opened with 'failed'})) "how to interact with ajax" ends here Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.