This article refers to and quotes "Sharp JQuery" to provide a detailed explanation of jQuery-Ajax and its main methods.
a. Does not require any browser plug-ins <br/>Does not require any browser plug-ins and can be supported by most browsers. Users only need to allow JavaScript on the browser Just execute.
b. Excellent user experience.
The biggest advantage is that the data can be updated without refreshing the entire page, which allows the Web application to quickly respond to user operations.
c. Improve the performance of Web programs <br/>Compared with the traditional mode, the biggest difference in performance of the Ajax mode is the way of transmitting data. In the traditional mode, data submission is realized through the form (from), and the data What is obtained is to obtain the content of the entire page by fully refreshing the web page. The Ajax mode only submits the data that needs to be submitted to the server through the XMLHttpRequest object, that is, it is sent on demand.
d. Reduce the burden on servers and broadband
The working principle of Ajax is equivalent to adding an intermediary layer between the user and the server, which asynchronousizes user operations and server responses. It creates an Ajax engine on the client and transfers some of the work burdened by the server in the traditional way to the client. , which facilitates client resources to be processed and reduces the burden on servers and broadband.
a. Insufficient browser support for the XMLHttpRequest object
One of the shortcomings of Ajax first comes from the browser. Only IE5.0 and later versions support the XMLHttpRequest object (most clients at this stage are IE6 or above). Mozilla, Netscape and other browsers support XMLHttpRequest later. To make Ajax applications run normally in various browsers, programmers must spend a lot of effort coding to take into account the differences between browsers, so that Aajx applications can be better compatible with various browsers.
b. Destroy the normal functions of the browser's forward and back buttons <br/>In Ajax, the functions of the forward and back buttons will be invalid. Although certain methods (adding anchor points) can be used to enable users to use the forward and back buttons, But compared to the traditional method, it is a lot more troublesome. For users, they often encounter this situation. When they click a button to trigger an Ajax interaction, they feel that they don’t want to do it, and then they habitually click the back button. , the most undesirable result occurred. The browser returned to a previous page, and the content obtained through Ajax interaction completely disappeared.
c. Insufficient support for search engines <br/>Usually search engines use crawlers to search and organize billions of massive data on the Internet. However, crawlers cannot yet understand those strange JavaScript codes and therefore The changes in page content caused by Ajax make sites using Ajax at a disadvantage compared to traditional sites in network promotion.
d. Lack of development and debugging tools
JavaScript is an important part of Ajax. At present, due to the lack of good JavaScript development and debugging tools, many web developers are afraid of JavaScript. This makes writing Ajax code even more difficult. Warriors, many web developers are now used to it. She is afraid of using visual tools and writing code herself, which has affected everyone's application of Ajax to a certain extent.
Ajax method needs to interact with the Web server, so it requires an environment. AppServe is a toolkit for installing the environment.
Download address: https://www.appserv.org/en/download/Installation
: Press the Next button on a single machine continuously and enter common information such as website address, email address, password, etc. The default port is 80.
Enter "http://localhost:80" in the browser, and the following interface will appear, indicating that the installation is successful.
Usage: Copy the written program to the installed AppServwww folder, and then enter "http://loaclhost:80/program file name" in the address bar to access it.
The jQuery library has a complete Ajax compatible suite. The functions and methods inside allow us to load data from the server without refreshing the browser.
https://www.w3school.com.cn/jquery/jquery_ref_ajax.asp
In the picture above,
. get () and
and $.getJSON() methods.
has previously published an article "Detailed explanation of jquery ajax-ajax() method".
For details, please click: https://juejin.cn/post/7019188063704350756
is different from other
methodsMethod, the simplest and most commonly used, can load remote HTML code and insert it into the DOM.
Structure
load( url , [data] , [callback] )
parameters
Application
1) Loading HTML documents
First build an HTML file (test.html) that is loaded by the load() method and appended to the page. The HTML code is as follows:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Test</title> </head> <body> <div> <p>hello world!</p> <ul> <li>C</li> <li>C#</li> <li>C++</li> <li>Java</li> <li>.Net</li> <li>JSP</li> <li>ASP</li> <li>PHP</li> <li>Python</li> <li>ios</li> <li>Android</li> <li>Javascript</li> <li>CSS</li> <li>HTML</li> <li>XML</li> <li>VUE</li> <li>React</li> <li>Angular</li> <li>SQL</li> </ul> </div> </body> </html>
Then create a new blank page (main.html), including the button that triggers the Ajax event, and the id "content"
used to display the appended HTML content (test.html). The code is as follows:<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="jquery/jquery-2.1.1.js"></script> <title>main</title> </head> <body> <!-- load() method --> <button id="btn1">Click to load</button> <h1>Loaded content:</h1> <div id="content1"></div> </body> </html>
Next write the jQuery code. After the DOM is loaded, call the load method by clicking the button to load the content in test.html into the element with the id "content". The code is as follows:
<script type="text/javascript"> $(function(){ // load(url) method $("#btn1").click(function(){ $("#content1").load("test.html")//Load the content of test.html to the current page when clicked }) }) </script>Before loading
the running results
:
After loading:
2) Filter the loaded HTML documents.
The above example is to load all the content in test.html into the element with the id "content" in main.html. If you only want to load certain content, you can use load(url selector) to achieve.
Note: There is a space between the url and the selector.
For example, to only load the content of the p tag in test.html, the code is as follows:
<script type="text/javascript"> $(function(){ // load(url, selector) filter $("#btn1").click(function(){ $("#content1").load("test.html p") }) }) </script>
Run results
3) Transfer mode
The load() method transfer mode is automatically specified based on the parameter data. If no parameters are passed, the GET method is used; otherwise, it is automatically converted to the POST method.
// load(url,fn) method, no parameter transfer, GET method $("#btn1").click(function(){ $("#content1").load("test.html", function(){ // code }) }) // load(url,fn) method, there are parameters to pass, POST method $("#btn1").click(function(){ $("#content1").load("test.html", {name: "peiqi", age: "18"}, function(){ // code }) })
4) Callback parameters
For operations that must be continued after loading is completed, the load() method provides a callback function (callback). This function has 3 parameters, representing "request returned content" and "request status". "XMLHttpRequest object", the code is as follows:
$("#content1").load("test.html p", function(responseText, textStates, XMLHttpRequest) { //responseText: Content returned by the request //textStates: Request status: success error notmodified timeout 4 types //XMLHttpRequest: XMLHttpRequest object});
Note: In the load() method, regardless of whether the Ajax request is successful, as long as the request is completed (complete) , the callback function (callback) will be triggered.
load() usually obtain static data files from the web server. If you need to pass some parameters to the page in the server, you can use
method (or $.ajax() method).
Notice:
() method are global functions in jQuery.
1) $.get() method
The $.get() method uses the GET method to make asynchronous requests.
Structure
$.get(url, [data], [callback], [type])
parameters
The application
below is a piece of HTML code for a comment page, which introduces the use of the $.get() method. The code is as follows:
<!-- $.get() and $.post() methods --> <h3>Comments</h3> <p>Name:<input type="text" name="" id="name"></p> <p>Content:<textarea id="content2"></textarea></p> <button id="btn2">Leave a message</button> <div id="msg"></div>
The page generated by this code is as shown in the figure:
After filling in your name and content, you can submit your comment.
a. First, you need to determine the requested URL address.
$("#btn2").click(function(){ $.get("test.php", data parameter, callback function) })
b. Before submitting, pass the name and content values to the background as parameter data.
$("#btn2").click(function(){ $.get("test.php", {"username":$("#name").val(), "content":$("#content2").val()}, callback function) })
c. If the server receives the passed data and returns successfully, the returned data can be displayed on the page through the callback function.
The callback function of the $.get() method has only two parameters
function(){ //data: The returned content can be XML documents, json files, XHML fragments, etc. //textStatus: Request status: success error notmodified timeout 4 types}
d. The data parameter represents the content returned by the request, and the textStatus parameter represents the request status. And the callback function can only be called when the data is successful (load() is called regardless of success or failure).
// $.get() method$("#btn2").click(function(){ $.get("test.php", {"username":$("#name").val(),"content":$("#content2").val()}, function(data,textStatus) { if(textStatus=="success"){ //success // code $(data).appendTo("#msg") } }, "html")//type })
e. Operation results
2) The $.post() method
has the same structure and usage as the $.get() method, but there are still the following differences:
a. The GET method will pass the parameters after the URL and the data will be browsed The server caches it, while the POST method is sent to the server as the entity content of the HTTP message (that is, wrapped in the request body). It can be seen that the security of the POST method is higher than that of the GET method.
b. The GET method has a size limit on the transmitted data (usually no larger than 2KB), while the POST method has no size limit in theory.
c. The data transferred by GET method and POST method are obtained differently on the server side. In PHP, data in GET mode can be obtained with "_GET[]", while data in POST mode can be obtained with " _POST[]". Both methods can be obtained using "$_REQUEST[]".
d. The transmission speed of GET method is higher than that of POST method.
Since all data submitted by POST and GET methods can be obtained through $_REQUEST[], so as long as the jQuery function is changed, the program can be switched between GET requests and POST requests. The code is as follows:
// $.post() method $("#btn2").click(function(){ $.post("test.php", {"username":$("#name").val(),"content":$("#content2").val()}, function(data,textStatus) { if(textStatus=="success"){ //success // code $(data).appendTo("#msg") } }, "html")//type })
In addition, when the load() method is passed with parameters, the POST method will be used to send the request. Therefore, you can also use the load() method to complete the same function. The code is as follows:
$("#btn2").click(function(){ $("#msg").load("test.php", { "username":$("#name").val(), "content":$("#content2").val() }); })
4.
) method
Sometimes, it is completely unnecessary to get all the JavaScript files needed when the page is first loaded. Although you can dynamically create
$(document.createElement("script")).attr("src", "test.js").appendTo("head"); //Or $("<script type='text/javascript' src='test.js' />").appendTo("head");
But this method is not ideal. jQuery provides the $.getScript() method to directly load js files, which is as simple and convenient as loading an HTML fragment, and does not require processing of JavaScript files, as the JavaScript files will be executed automatically.
Structure
$.getScript( url , fn ); //url: request address //fn: callback function
application <br/>Create a nowDate.js file to get the current date. The code is as follows:
function getNowDate(){ var date = new Date return date; }
When the "Get Current Time" button is clicked, the latest time and date are displayed. The code is as follows:
//HTML code <!-- $.getScript() method --> <button id="btn3">Click to get the time</button> <div id="message1"></div> //jQuery code// $.getScript() method $("#btn3").click(function(){ $.getScript("nowDate.js", function(){ var date1 = getNowDate(); //Call the getNowDate() method in nowDate.js to get the date var txtHtml= "<div>"+ date1 + "</div>"; $("#message1").html(txtHtml); }) })
Before loading
the running results
:After loading:
2) $.getJSON() method
the .getScript() method.
Structure
$.getJSON(url,fn); //url: request address //fn: callback function
application
creates a new test.json file, the code is as follows:
{ "helen":{ "sex":"woman", "age":18, "weight":"50kg", "height":"165cm" }, "peter":{ "sex":"man", "age":28, "weight":"65kg", "height":"185cm" } }
Create a new HTML file with the following code:
<!-- $.getJSON() method --> <button id="btn4">Click to load JSON file</button> <div id="message2"></div>
When you click the load button, no effect can be seen on the page. You can view it on the console. The code is as follows:
// $.getJSON() method $("#btn4") .click(function(){ $.getJSON("test.json", function(data){ console.log(data); //The console outputs the returned data}) })
The console output is as shown in the figure:
Although the above function loads the JSON file (test.json), it does not tell JavaScript how to process the returned data, so we can process the returned data in the callback function.
Usually we need to iterate through the data we get. Although we can use the traditional for loop here, we can also pass
The .each() function takes an array or object as the first parameter and a callback function as the second parameter. The callback function has Two parameters, the first one is the member of the object or the subscript of the array, the second bit corresponds to the variable or content, the code is as follows:
// $.getJSON() method $("#btn4").click(function() { $.getJSON("test.json", function(data){ console.log(data); //The console outputs the returned data //Processes the returned data var txtHtml = ""; $.each(data, function(index, item){ txtHtml += "<div><h4>" + index + ":</h4><ul><li>sex:" + item["sex"] + "</li><li>age:" + item["age"] + "</li><li>weight:" + item["weight"] + "</li><li>height:" + item["height"] + "</li></div>"; }) $("#message2").html(txtHtml); }) })
The effect is as shown in the figure:
before loading:
After loading:
[Recommended learning: jQuery video tutorial, web front-end video]
The above is to talk about Ajax in jQuery and explain the details of its main methods. For more, please pay attention to other related articles on the PHP Chinese website!