Table of Contents
Preface
1. Advantages and Disadvantages of Ajax
1. Advantages of Ajax
2. Shortcomings of Ajax
2. Install the Web environment---AppServ
3. jQuery Ajax operation function
加载的内容:
.get()方法和.get() 方法和.post() 方法" >3、.get()方法和.get() 方法和.post() 方法
评论
Home Web Front-end JS Tutorial Let's talk about Ajax in jQuery and explain its main methods in detail

Let's talk about Ajax in jQuery and explain its main methods in detail

Mar 15, 2022 am 11:12 AM
ajax jquery

This article will take you to understand Ajax in jQuery, talk about the advantages and disadvantages of Ajax, and have an in-depth understanding of the main methods of Ajax. I hope it will be helpful to everyone!

Let's talk about Ajax in jQuery and explain its main methods in detail

Preface

This article refers to and quotes "Sharp JQuery" to provide a detailed explanation of jQuery-Ajax and its main methods.

1. Advantages and Disadvantages of Ajax

1. Advantages of Ajax

a. No browser plug-ins are required
No need for any Browser plug-ins are supported by most browsers, and users only need to allow JavaScript to execute on the browser.

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 respond quickly to user operations.

c. Improve the performance of Web programs
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 It is implemented through the form (from), and the data is obtained by fully refreshing the web page to obtain the content of the entire 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 the server and broadband
The working principle of Ajax is equivalent to adding an intermediate layer between the user and the server, which asynchronously asynchronousizes user operations and server responses. , he creates an Ajax engine on the client side, transferring some of the traditional server burden work to the client, making it easier for client resources to be processed, and reducing the burden on the server and broadband.

2. Shortcomings of Ajax

a. The browser’s insufficient support for the XMLHttpRequest object
One of the shortcomings of Ajax first comes from the browser, IE5. 0 and later versions only support the XMLHttpRequest object (most clients at this stage are above IE6). Mozilla, Netscape and other browsers support XMLHttpRequest even later. In order to enable Ajax applications to run normally in various browsers, the program Developers must spend a lot of effort coding to take into account the differences between browsers, so that Aajx applications can be better compatible with each browser.

b. Destroy the normal functions of the browser's forward and back buttons
In Ajax, the functions of the forward and back buttons will be invalid, although it can be done through certain methods (adding anchor points ) to enable users to use the forward and back buttons, but it is a lot more troublesome than the traditional method. For users, they often encounter this situation. When clicking a button to trigger an Ajax interaction, they feel that they do not want to do so. , and then habitually clicked the back button, and the most undesirable result occurred. The browser returned to the previous page, and the content obtained through Ajax interaction completely disappeared.

c. Insufficient support for search engines
Usually search engines use crawlers to search and organize billions of massive data on the Internet. However, crawler programs It is still not possible to understand those strange JavaScript codes and the resulting changes in page content, which puts Ajax-based sites 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 Being intimidated by JavaScript makes writing Ajax code even more difficult. Warrior, many web developers are currently accustomed to using visual tools and are afraid of writing code themselves. This has affected everyone's application of Ajax to a certain extent.

2. Install the Web environment---AppServ

The 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: Single-machine Next button, enter common information such as website address, email address, password, etc., port The default is 80.

Enter "http://localhost:80" in the browser, and the following interface will appear, indicating that the installation is successful.

Lets talk about Ajax in jQuery and explain its main methods in detail

Usage: Copy the written program to the installed AppServ\www folder, and then enter "http://loaclhost:80/" in the address bar Program File Name" to access.

3. jQuery Ajax operation function

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

Lets talk about Ajax in jQuery and explain its main methods in detail

In the picture above, .Ajax()The method isjQu# The lowest method in ##ery, the layer 2 is .load(),.Ajax() method is the lowest method in jQuery, the second layer is .load(), layer is. load(), .get() and .po (

)

,

3

layer

is

.getScript() and $.getJSON() methods. Lets talk about Ajax in jQuery and explain its main methods in detail

1. $.ajax() method

I have previously published an article "Detailed explanation of jquery ajax-ajax() method"

For details, please click: https:/ /juejin.cn/post/7019188063704350756

2. The load() method

is the simplest and most commonly used method compared to other methods. It can load remote HTML code and insert it into the DOM.

Structure

load( url , [data] , [callback] )
Copy after login

Parameters

ApplicationLets talk about Ajax in jQuery and explain its main methods in detail

1) Load HTML document #########First build an HTML file (test.html) 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>测试</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 after login
###Then create a new blank page (main.html), including the button that triggers the Ajax event, and the ###### with the id "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.js"></script>
	<title>main</title>
</head>
<body>
	<!-- load() 方法 -->
	<button id="btn1">点击加载</button>
	<h1 id="加载的内容">加载的内容:</h1>
	<div id="content1"></div>
</body>
</html>
Copy after login
###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)方法
		$("#btn1").click(function(){
    		$("#content1").load("test.html")//单击时将test.html的内容加载到当前页面上
   		})
	})
</script>
Copy after login
######Run result#### #####Before loading:###############After loading:###

Lets talk about Ajax in jQuery and explain its main methods in detail

2)筛选载入的HTML文档

上面例子是将 test.html 中的内容全部都加载到 main.html 中 id 为 ”content“ 的元素中,如果只想加载某些内容,可以使用 load( url selector ) 来实现。

注意:url 和选择器之间有一个空格。

例如只加载 test.html 中 p 标签的内容,代码如下:

<script type="text/javascript">
    $(function(){
	// load(url, selector)筛选
	$("#btn1").click(function(){
    	    $("#content1").load("test.html p")
   	})
    })
</script>
Copy after login

运行结果

Lets talk about Ajax in jQuery and explain its main methods in detail

3)传递方式

load() 方法传递方式根据参数 data 来自动指定。如果没有参数传递,则采用 GET 方式,反之,则自动转换为 POST 方式。

// load(url,fn)方法,无参数传递,GET方式
$("#btn1").click(function(){
    $("#content1").load("test.html", function(){
    	// code
    })
})

// load(url,fn)方法,有参数传递,POST方式
$("#btn1").click(function(){
    $("#content1").load("test.html", {name: "peiqi", age: "18"}, function(){
    	// code
    })
})
Copy after login

4)回调参数

对于必须在加载完成后才能继续的操作,load() 方法提供了回调函数(callback),该函数有3个参数,分别代表“请求返回的内容”,“请求状态”,“XMLHttpRequest对象”,代码如下:

$("#content1").load("test.html p",function(responseText,textStates,XMLHttpRequest){
   //responseText:请求返回的内容
   //textStates:请求状态:success   error  notmodified  timeout4种
   //XMLHttpRequest:XMLHttpRequest对象
  });
Copy after login

注意:在 load() 方法中,无论Ajax请求是否成功,只要请求完成(complete),回调函数(callback)都会被触发。

3、.get()方法和.get() 方法和.post() 方法

load() 通常是从web服务器上获取静态的数据文件,如果需要传递一些参数给服务器中的页面,可以使用 .get()方法和.get() 方法和.post() 方法(或 $.ajax() 方法)。

注意:.get()方法和.get() 方法和.post() 方法是 jQuery 中的全局函数。

1)$.get() 方法

$.get() 方法使用 GET 方式来进行异步请求。

结构

$.get( url,[ data ],[ callback ],[ type ])
Copy after login

参数

Lets talk about Ajax in jQuery and explain its main methods in detail

应用

下面是一段评论页面的 HTML 代码,通过该段代码来介绍 $.get() 方法的使用。代码如下:

 <!-- $.get() 和 $.post() 方法 -->
<h3 id="评论">评论</h3>
<p>姓名:<input type="text" name="" id="name"></p>
<p>内容:<textarea id="content2"></textarea></p>
<button id="btn2">发表留言</button>
<div id="msg"></div>
Copy after login

该段代码生成的页面如图所示:

Lets talk about Ajax in jQuery and explain its main methods in detail

将姓名和内容填写好后,就可以提交评论了。

a.首先需要确定请求的 URL 地址。

$("#btn2").click(function(){
    $.get("test.php", data参数, 回调函数)
})
Copy after login

b.提交之前,将姓名和内容的值作为参数 data 传递给后台。

$("#btn2").click(function(){
    $.get("test.php",  {"username":$("#name").val(), "content":$("#content2").val()}, 回调函数)
})
Copy after login

c.如果服务器接收到传递的 data 数据并成功返回,那么就可以通过回调函数将返回的数据显示到页面上。

$.get() 方法的回调函数只有两个参数

function(){
  //data:返回的内容,可以是XML文档,json文件,XHML片段等等
  //textStatus:请求状态:success  error  notmodified timeout 4种
}
Copy after login

d. data 参数代表请求返回的内容,textStatus 参数代表请求状态,而且回调函数只有当数据成功(success)后才能被调用( load() 是不管成功还是失败都被调用 )。

// $.get()方法
$("#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 after login

e.运行结果

Lets talk about Ajax in jQuery and explain its main methods in detail

2)$.post() 方法

它与 $.get() 方法的结构和使用方式都相同,不过之间仍然有以下区别:

a. GET 方式会将参数跟在 URL 后进行传递且数据会被浏览器缓存起来,而 POST 方式则是作为 HTTP 消息的实体内容(也就是包裹在请求体中)发送给服务器,由此可见 POST 方式的安全性高于 GET 方式。

b. GET 方式对传输的数据有大小限制(通常不能大于2KB),而 POST 方式理论上大小不限制。

c. GET 方式与 POST 方式传递的数据在服务器端的获取不相同。在 PHP 中,GET 方式的数据可用 "\_GET\[\]" 获取,而 POST 方式可以用 "_POST[]" 获取。2种方式都可用 "$_REQUEST[]" 来获取。

d. GET 方式的传输速度高于 POST 方式。

由于 POST 和 GET 方式提交的所有数据都可以通过 $_REQUEST[] 来获取,因此只要改变jQuery函数,就可以将程序在 GET 请求和 POST 请求之间切换,代码如下:

// $.post()方法
$("#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 after login

另外,当 load() 方法带有参数传递时,会使用 POST 方式发送请求。因此也可以使用 load() 方法来完成同样的功能,代码如下:

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

4、.getScript()方法和.getScript() 方法和.getJson() 方法

1)$.getScript() 方法

有时候,在页面初次加载时就获取所需的全部 JavaScript 文件是完全没有必要的。虽然可以在需要哪个 JavaScript 文件时,动态创建

$(document.createElement("script")).attr("src", "test.js").appendTo("head");
//或者
$("<script type=&#39;text/javascript&#39; src=&#39;test.js&#39; />").appendTo("head");
Copy after login

但这种方式并不理想。jQuery 提供了 $.getScript() 方法来直接加载 js 文件,与加载一个 HTML 片段一样简单方便,并且不需要对 JavaScript 文件进行处理,JavaScript 文件会自动执行。

结构

 $.getScript( url , fn ); 
 //url:请求地址
 //fn:回调函数
Copy after login

应用
新建一个 nowDate.js 文件,获取当前日期,代码如下:

function getNowDate(){
    var date = new Date
    return date;
}
Copy after login

点击“获取当前时间”按钮时 ,显示最新时间日期,代码如下:

//HTML代码
<!-- $.getScript() 方法 -->
<button id="btn3">点击获取时间</button>
<div id="message1"></div> 
    
//jQuery代码
// $.getScript()方法
$("#btn3").click(function(){
    $.getScript("nowDate.js", function(){
    	var date1 = getNowDate(); //调用nowDate.js中的getNowDate()方法获取日期
    	var txtHtml= "<div>"+ date1 + "</div>";
    	$("#message1").html(txtHtml);
    })
})
Copy after login

运行结果

加载前:

Lets talk about Ajax in jQuery and explain its main methods in detail

加载后:

1Lets talk about Ajax in jQuery and explain its main methods in detail

2)$.getJSON() 方法

.getJSON()方法用于加载JSON文件,与.getJSON() 方法用于加载JSON文件,与.getScript() 方法的用法相同。

结构

$.getJSON( url , fn);
//url:请求地址
//fn:回调函数
Copy after login

应用

新建一个 test.json 文件,代码如下:

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

新建一个 HTML 文件,代码如下:

<!-- $.getJSON() 方法 -->
<button id="btn4">点击加载JSON文件</button>
<div id="message2"></div>
Copy after login

当点击加载按钮时,页面上看不到任何效果,可以在控制台查看,代码如下:

// $.getJSON()方法
$("#btn4").click(function(){
    $.getJSON("test.json", function(data){
    	console.log(data); //控制台输出返回的数据
    })
})
Copy after login

控制台输出如图:

1Lets talk about Ajax in jQuery and explain its main methods in detail

以上虽然函数加载了 JSON 文件(test.json),但是并没有告知 JavaScript 对返回的数据如何处理,所以在回调函数里我们可以处理返回的数据。

通常我们需要遍历我们得到的数据,虽然这里我们可以使用传统的for循环,但是我们也可以通过 .each(),可以用来遍历对象和数组,.each(),可以用来遍历对象和数组,.each() 函数是以一个数组或者对象为第1个参数,以一个回调函数作为第2个参数,回调函数拥有两个参数,第1个为对象的成员或者数组的下标,第2个位对应变量或内容,代码如下:

// $.getJSON()方法
$("#btn4").click(function(){
    $.getJSON("test.json", function(data){
    	console.log(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);
    })
})
Copy after login

效果如图:

加载前:

1Lets talk about Ajax in jQuery and explain its main methods in detail

加载后:

1Lets talk about Ajax in jQuery and explain its main methods in detail

【推荐学习:jQuery视频教程web前端视频

The above is the detailed content of Let's talk about Ajax in jQuery and explain its main methods in detail. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

PHP vs. Ajax: Solutions for creating dynamically loaded content PHP vs. Ajax: Solutions for creating dynamically loaded content Jun 06, 2024 pm 01:12 PM

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

PHP and Ajax: Ways to Improve Ajax Security PHP and Ajax: Ways to Improve Ajax Security Jun 01, 2024 am 09:34 AM

In order to improve Ajax security, there are several methods: CSRF protection: generate a token and send it to the client, add it to the server side in the request for verification. XSS protection: Use htmlspecialchars() to filter input to prevent malicious script injection. Content-Security-Policy header: Restrict the loading of malicious resources and specify the sources from which scripts and style sheets are allowed to be loaded. Validate server-side input: Validate input received from Ajax requests to prevent attackers from exploiting input vulnerabilities. Use secure Ajax libraries: Take advantage of automatic CSRF protection modules provided by libraries such as jQuery.

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

See all articles