Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

The preface

This article takes a look at jQUERy-Ajax and its main methods with reference to Sharp JQuery.

The advantages and disadvantages of Ajax

1. Advantages of Ajax

This is supported by most browsers without any browser plugins. The user just needs to allow JavaScript to run on the browser.

B. Excellent user experience. The biggest advantage, the ability to update data without refreshing the entire page, enables Web applications to respond quickly to user actions.

C. Improve the performance of Web applications. Compared with the traditional mode, the biggest difference in the performance of Ajax mode lies in the way of data transmission. In the traditional mode, data submission is realized through a form, while data acquisition is obtained by refreshing the entire page. The Ajax mode simply delivers the data that needs to be submitted to the server side via the XMLHttpRequest object, that is, on demand.

D. Reduce the burden of the server and broadband Ajax work principle is equivalent to adding an intermediate layer between the user and the server, is the user operation and server response asynchronous, he created Ajax engine in the client side, the traditional way of some of the server burden of the work transferred to the client side, easy to handle the client resources. Lighten the load on servers and broadband.

2. Ajax shortcomings

One of the drawbacks of Ajax is that browsers support THE XMLHttpRequest object. IE5.0 and later support the XMLHttpRequest object (most clients are IE6 or later), Mozilla, Web-browsers such as Netscape supported XMLHttpRequest more recently, and in order for Ajax applications to work properly across browsers, programmers had to spend a lot of effort coding to make Aajx applications more compatible across browsers.

B. destroy the browser, the normal functions of the back button In Ajax, forward and backward button function failure, while it is possible through a certain method (add anchor) to make the user can use the forward and backward buttons, but compared with the traditional way is a lot of trouble, for the user, they often encounter this situation, When you click a button to trigger an Ajax interaction and then decide you don’t want to do it, you habitually click the back button, and you get the most undesirable result: the browser resets to a previous page and the content gained through the Ajax interaction disappears completely.

C. Insufficient support for search engines. Search engines usually use crawlers to search and organize billions of tons of data on the Internet. However, crawlers are not able to understand the strange JavaScript code and the resulting changes in page content. This puts Ajax-enabled sites at a disadvantage to traditional sites when it comes to web 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, which is even more difficult to write Ajax code. Warrior. many Web developers are used to visual tools and are afraid to write their own code, but she has influenced the use of Ajax to some extent.

Install the Web environment -AppServ

Ajax methods need to interact with the Web server side, so you need an environment, and AppServe is the toolkit for installing the environment.

Download address: www.appserv.org/en/download…

Installation: single machine Next button continuously, input url, email, password and other common information, the default port is 80.

Enter http://localhost:80 in the browser. If the following page is displayed, the installation is successful.

Use: copy the written program to the installed AppServ\ WWW folder, and then enter “http://loaclhost:80/ program file name” in the address bar can be accessed.

JQuery Ajax manipulation functions

The jQuery library has a complete ajax-compatible suite. The functions and methods allow you to load data from the server without refreshing the browser.

www.w3school.com.cn/jquery/jque…

In the figure above, the.ajax () method is the lowest level method in jQuery, the.load() method is the lowest level method in jQuery, the.ajax () method is the lowest level method in jQuery, the.load() method is the lowest level method in jQuery, the.ajax () method is the lowest level method in jQuery, and the.ajax () method is the lowest level method in jQuery. The.get() and.post() methods, layer 3 is the.post() method, layer 3 is the.post() method, layer 3 is the.getScript() and $.getjson () methods.

1. $.ajax() method

Jquery Ajax-Ajax () method

Please refer to juejin.cn/post/701918…

2. Load () method

The simplest and most common method compared to the others is to load remote HTML code and insert it into the DOM.

structure

load( url , [data] , [callback] )
Copy the code

parameter

application

1) Load the HTML document

First build an HTML file (test.html) that is loaded by the load() method and appended to the page. The HTML code looks like this:

<! DOCTYPE HTML > < HTML > <head> <meta charset=" UTF-8 "> <title> </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>Copy the code

Then create a new blank page (main.html) with a button that triggers the Ajax event and an ID of “Content.

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.1.js "></script> <title>main</title> </head> <body> <! - the load () method -- -- > < button id = "btn1" > click load < / button > < h1 > load content: < / h1 > < div id = "content1" > < / div > < / body > < / HTML >Copy the code

Next, write the jQuery code. After the DOM is loaded, click the button to call the load method and load the contents of test.html into the element with the id “Content” as follows:

<script type="text/javascript"> $(function(){// load(url) method $("#btn1").click(function(){ $("#content1").load("test.html")// Load the contents of test.html to the current page when clicked})}) </script>Copy the code

The results

Before loading:

After the load:

2) Filter loaded HTML documents

The example above is to load all the contents of test. HTML into the element whose ID is “content” in main. HTML. If you want to load only some content, you can use load(URL selector) to do this.

Note: There is a space between the URL and the selector.

For example, load only the contents of the p tag in test. HTML as follows:

<script type="text/javascript"> $(function(){ // load(url, The selector) screening $(" # btn1 "). Click (function () {$(" # content1 "). The load (" test. HTML p ")})}) < / script >Copy the code

The results

3) Mode of delivery

The load() method is automatically specified based on the data parameter. If no parameter is passed, the GET mode is adopted; otherwise, the POST mode is automatically converted.

// load(url,fn) method, no argument passed, GET way $(" # btn1 "). Click (function () {$(" # content1 "). The load (" test. HTML ", function () {/ / code})}) / / the load (url, fn) method, a parameter passing, POST way $(" # btn1 "). Click (function () {$(" # content1 "). The load (" test. HTML, "{name:" peiqi ", the age: "18"}, function(){ // code }) })Copy the code

4) Callback parameters

For operations that must continue after loading, the load() method provides a callback function that takes three parameters, representing “what is returned by the request”, “request status”, and “XMLHttpRequest object”, as follows:

$("#content1").load("test.html p", function (responseText, textStates, XMLHttpRequest) {//responseText: //XMLHttpRequest: XMLHttpRequest object});Copy the code

Note: In the Load () method, the callback is fired whenever the request completes, regardless of whether the Ajax request succeeds or not.

3,
. g e t ( ) Methods and And.get () method
.post () method

Load () usually gets static data files from a Web server, and if you need to pass some parameters to a page in the server, you can use the.get() and.get() methods and.get() and.post() methods (or $.ajax()).

Get () and.get() and.get() and.post() are global functions in jQuery.

1) $.get(

The $.get() method uses get to make asynchronous requests.

structure

$.get(url, [data], [callback], [type])Copy the code

parameter

application

Here is the HTML code for the comment page that illustrates the use of the $.get() method. The code is as follows:

<! - $. Get () and $. Post () method -- -- > < h3 > comments < / h3 > < p > name: < input type = "text" name = "" id =" name "> < / p > < p > content: < textarea Id = "content2 >" < / textarea > < / p > < button id = "btn2" > published comments < / button > < div id = "MSG" > < / div >Copy the code

The page generated by this code looks like this:

Once you’ve filled in your name and content, you can submit a comment.

A. Determine the REQUESTED URL.

$(" # btn2 "). Click (function () {$.get (" test. PHP ", the data parameter, the callback function)})Copy the code

B. Before submission, pass the name and content values to the background as data.

$(" # btn2 "). Click (function () {$.get (" test. PHP, "{" username" : $(" # name "). Val (), "content" : $(" # content2 "). Val ()}, the callback function)})Copy the code

C. If the server receives the passed data and returns it successfully, the returned data can be displayed on the page via a callback function.

The $.get() callback takes only two arguments

Function (){//data: return the contents of the request, such as XML document, JSON file, XHML fragment, etc. //textStatus: request status: success error notModified timeout 4}Copy the code

The d. data argument represents the content returned by the request, the textStatus argument represents the request status, and the callback function cannot be called until the data succeeds (load() is called regardless of success or failure).

/ / $. The 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 })Copy the code

E. Running result

2) $.post(

It is structured and used in the same way as the $.get() method, but there are some differences:

A. In GET mode, parameters are transmitted after the URL and the data is cached by the browser. In POST mode, the data is sent to the server as the entity content of the HTTP message (that is, wrapped in the request body).

B. The GET mode has a size limit (usually no larger than 2KB) on the data to be transferred, while the POST mode has no size limit.

C. The server obtains data in GET mode and POST mode differently. In PHP, GET data can be retrieved with “\_GET\[\]”, while POST data can be retrieved with “_POST[]”. Either method can be obtained with “$_REQUEST[]”.

D. The transfer speed of GET is higher than that of POST.

$_REQUEST[] = $_REQUEST[] $_REQUEST[] = $_REQUEST[] $_REQUEST[] = $_REQUEST[]

/ / $. 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 })Copy the code

In addition, when the Load () method is passed with parameters, the request is sent using POST. So you can use the load() method to do the same thing:

$("#btn2").click(function(){
	$("#msg").load("test.php", {
    	"username":$("#name").val(),
        "content":$("#content2").val()
    });
})
Copy the code

4,
. g e t S c r i p t ( ) Methods and And getScript () method
The getJson () method

1) $.getScript()

Sometimes it’s not necessary to get all the JavaScript files you need when the page first loads. Although you can create JavaScript files dynamically when you need them

$(document.createElement("script")).attr("src", "test.js").appendTo("head"); / / or $(" < script type = 'text/javascript' SRC = 'test. Js' / > "). The appendTo (" head ");Copy the code

But this approach is not ideal. JQuery provides the $.getScript() method to load the JS file directly, which is as easy and convenient as loading an HTML fragment, and does not require processing of the JavaScript file, which is automatically executed.

structure

$.getScript( url , fn ); //fn: callback functionCopy the code

Create a nowDate.js file and get the current date as follows:

function getNowDate(){
    var date = new Date
    return date;
}
Copy the code

When clicking “Get current time” button, the latest time and date will be displayed with the following code:

/ / HTML <! </button> <div id="message1"></div> $.getScript() $("#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); })})Copy the code

The results

Before loading:

After the load:

$.getjson () method

The.getjson () method is used to load a JSON file, and the.getjson () method is used to load a JSON file, the same as the.getscript () method.

structure

$.getJSON( url , fn); //fn: callback functionCopy the code

application

Create a new test.json file with the following code:

{
    "helen":{
	"sex":"woman",
	"age":18,
	"weight":"50kg",
	"height":"165cm"
    },
    "peter":{
	"sex":"man",
	"age":28,
	"weight":"65kg",
	"height":"185cm"
    }
}
Copy the code

Create a new HTML file with the following code:

<! </button> <div id="message2"></div>Copy the code

When you click the load button, you will not see any effect on the page, you can view it in the console, the code is as follows:

$("#btn4").click(function(){$.getjson ("test.json", function(data){console.log(data); // Console output returns data})})Copy the code

Console output is shown as follows:

The above function loads the JSON file (test.json), but it does not tell JavaScript what to do with the returned data, so we can process the returned data in the callback function.

Usually we need to iterate over the data we’ve got, and although we can use a traditional for loop here, we can also iterate over objects and arrays with.each(), objects and arrays with.each(), objects and arrays with.each(), The.each() function takes an array or object as its first argument and a callback function as its second argument. The callback function takes two arguments: the first is the object’s member or array index, and the second bit corresponds to the variable or content:

$("#btn4").click(function(){$.getjson ("test.json", function(data){console.log(data); Var txtHtml = ""; $. Each (data, function index, the 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); })})Copy the code

The effect is as follows:

Before loading:

After the load:

Please feel free to discuss in the comments section. The nuggets will draw 100 nuggets in the comments section after the diggnation project. See the event article for details.