Home Web Front-end JS Tutorial Detailed explanation of the usage of jQuery Ajax (load, post, get, ajax)

Detailed explanation of the usage of jQuery Ajax (load, post, get, ajax)

Jan 23, 2018 pm 05:11 PM
ajax jquery post

This article mainly brings you a detailed discussion on the usage of jQuery Ajax (load, post, get, ajax). The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

Today I saw some netizens in the group asking about the differences between Jquery Ajax (load, post, get, ajax). Now I have compiled an article, hoping to help netizens. , first let’s look at some simple methods.

These methods are all methods that encapsulate jQuery.ajax() to facilitate our use. Of course, if you want to deal with complex logic, you still need to use jQuery .ajax() (this will be discussed later).

1. load(url, [data], [callback]): Load the remote HTML file code and insert it into the DOM.

url (String): The URL address of the requested HTML page.

data (Map): (optional parameter) key/value data sent to the server.

callback (Callback): (optional parameter) The callback function when the request is completed (does not need to be successful).

This method uses the GET method to pass by default. If the [data] parameter has data passed in, it will be automatically converted to the POST method. In jQuery 1.2, you can specify the selector,

to filter the loaded HTML document, and only the filtered HTML code will be inserted into the DOM. The syntax is like "url #some > selector".

This method can easily dynamically load some HTML files, such as forms.

Sample code:

$(".ajax.load").load("http:
//www.jb51.net",function (responseText, textStatus, XMLHttpRequest)
{this;//在这里this指向的是当前的DOM对象,
即$(".ajax.load")[0]
 //alert(responseText);
//请求返回的内容
/alert(textStatus);
//请求状态:success,error
//alert(XMLHttpRequest);
//XMLHttpRequest对象});
Copy after login

Note: I don’t know why writing an absolute path to a URL will cause an error under FF. If you know, please tell me. The get() and post() examples below use absolute paths, so under FF you will get an error and will not see the results returned. There are also get() and post() examples that are called cross-domain. I found that there was no way to get the results after uploading them, so I removed the run button.

2. jQuery.get( url, [data], [callback] ): Use GET method to make asynchronous requests

Parameters:

url (String): Send Requested URL address.

data (Map): (Optional) The data to be sent to the server, expressed in the form of Key/value pairs, will be appended to the request URL as QueryString.

callback (Function): (optional) Callback function when loading is successful (this method is called only when the return status of Response is success).

This is a simple GET request function to replace the complex $.ajax. The callback function can be called when the request is successful. If you need to execute a function on error, use $.ajax.

Sample code:

$.get("./Ajax.aspx", {Action:"get",Name:"lulu"},
function (data, textStatus)
{//返回的 data 可以是 xmlDoc, jsonObj, html, text, 等等.this; 
// 在这里this指向的是Ajax请求的选项配置信息,请参考下图alert(data);
//alert(textStatus);
//请求状态:success,error等等。
Copy after login

Of course, the error cannot be caught here, because the callback function will not be run at all when there is an error //alert(this);});

Click to send the request:

This in the jQuery.get() callback function points to the option configuration information of the Ajax request:

3. jQuery.post( url, [data], [ callback], [type] ): Use POST method to make asynchronous requests

Parameters:

url (String): URL address to send the request.

data (Map) : (Optional) The data to be sent to the server, expressed in the form of Key/value pairs.

callback (Function): (optional) Callback function when loading is successful (this method is called only when the return status of Response is success).

type (String): (Optional) The official description is: Type of data to be sent. In fact, it should be the type of client request (JSON, XML, etc.)

This is a simple POST request function to replace the complex $.ajax. The callback function can be called when the request is successful. If you need to execute a function on error, use $.ajax.

Sample code:

Ajax.aspx:

Response.ContentType = "application/json";Response.Write("{result: '" + Request["Name"] + ",你好!(这消息来自服务器)'}");
Copy after login

jQuery code:

$.post("Ajax.aspx", { Action: "post", Name: "lulu" },function (data, textStatus)
{// data 可以是 xmlDoc, jsonObj, html, text, 等等.//this; 
// 这个Ajax请求的选项配置信息,请参考jQuery.get()说到的thisalert(data.result);}, "json");
Copy after login

Click to submit:

The request is set here The format is "json":

If you set the request format to "json" and you do not set the ContentType returned by Response to: Response.ContentType = "application/json"; then you will not be able to capture it. to the returned data.

Note that alert(data.result); since the Accept header is set to "json", the data returned here is an object, and there is no need to use eval() to convert it into an object.

4. jQuery.getScript( url, [callback] ): Request to load and execute a JavaScript file through GET method.

Parameters

url (String): The address of the JS file to be loaded.

callback (Function): (optional) Callback function after successful loading.

Before jQuery 1.2, getScript could only call JS files in the same domain. In 1.2, you can call JavaScript files across domains. Note: Safari 2 or earlier cannot execute scripts synchronously in the global scope. If you add a script via getScript, please add a delay function.

This method can be used, for example, to load the JS files required by the editor when only the editor is focus(). Here are some sample codes:

Load and execute test.js.

jQuery code:

$.getScript("test.js");

Load and execute AjaxEvent.js, and display information after success.

jQuery code:

$.getScript("AjaxEvent.js", function(){alert("AjaxEvent.js is loaded and executed. Click the Get or Post button above See what's the difference? ");});

jQuery Ajax Event

Ajax requests generate several different events that we can subscribe to and process our logic in them. There are two types of Ajax events in jQuery: local events and global events.

Local events are defined within the method during each Ajax request, for example:

$.ajax({beforeSend: function(){// Handle the beforeSend event},complete : function(){// Handle the complete event}// ...});

The global event is triggered by every Ajax request. It will be broadcast to all elements in the DOM. Above The script loaded in the getScript() example is the global Ajax event. Global events can be defined as follows:

$("#loading").bind("ajaxSend", function(){$(this).show();}).bind("ajaxComplete", function( ){$(this).hide();});

Or:

$("#loading").ajaxStart(function(){$(this).show() ;});

We can disable global events in specific requests, just set the global option:

$.ajax({url: "test.html",global : false,//Disable global Ajax events.// ...});

The above article discusses the usage of jQuery Ajax (load, post, get, ajax) in detail, which the editor shared with This is all your content, I hope it can give you a reference, and I hope you will support Script House more.

Related recommendations:

Ajax usage simple tutorial

javascript jQuery $.post $.ajax usage

Super simple AJAX usage of jquery_jquery

The above is the detailed content of Detailed explanation of the usage of jQuery Ajax (load, post, get, ajax). 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 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 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

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.

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:

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:

How to implement PHP to jump to the page and carry POST data How to implement PHP to jump to the page and carry POST data Mar 22, 2024 am 10:42 AM

PHP is a programming language widely used in website development, and page jumps and carrying POST data are common requirements in website development. This article will introduce how to implement PHP page jump and carry POST data, including specific code examples. In PHP, page jumps are generally implemented through the header function. If you need to carry POST data during the jump process, you can do it through the following steps: First, create a page containing a form, where the user fills in the information and clicks the submit button. Acti in the form

PHP code example: How to use POST to pass parameters and implement page jumps PHP code example: How to use POST to pass parameters and implement page jumps Mar 07, 2024 pm 01:45 PM

Title: PHP code example: How to use POST to pass parameters and implement page jumps In web development, it often involves the need to pass parameters through POST and process them on the server side to implement page jumps. PHP, as a popular server-side scripting language, provides a wealth of functions and syntax to achieve this purpose. The following will introduce how to use PHP to implement this function through a practical example. First, we need to prepare two pages, one to receive POST requests and process parameters

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.

See all articles