search
HomeWeb Front-endJS TutorialHow to use the parameters of the $.Ajax() method

This time I will show you how to use the parameters of the $.Ajax() method, and what are the precautions for using the $.Ajax() method. The following is a practical case, let's take a look.

Let me first introduce to you the concept of Ajax

AJAX stands for "Asynchronous Javascript And XML" (Asynchronous JavaScript and XML), which refers to a Web development techniques for creating interactive web applications.

AJAX = Asynchronous JavaScript and XML (a subset of Standard Universal Markup Language).

AJAX is a technology for creating fast, dynamic web pages.

By exchanging a small amount of data with the server in the background, AJAX can enable asynchronous updates of web pages. This means that parts of a web page can be updated without reloading the entire page.

Traditional web pages (not using AJAX) must reload the entire web page if the content needs to be updated.

ajax method

$.ajax() method is the lowest level Ajax implementation of jQuery. Its structure is:

 $.ajax(options)

This method has only one parameter, but this object contains the request settings and callback functions required by the $.ajax() method. Information and parameters exist in the form of key/value, and all parameters are optional. Commonly used parameters are shown in the table below:

1.url

is required to be a String type parameter, (default is the current address) to send the requested page .

2.type

requires parameters of String type, and the request method (post or get) defaults to get. Note that other

http request methods, such as put and delete, can also be used, but are only supported by some browsers.

3.timeout

Requires a Number type parameter and sets the request timeout (milliseconds). This setting will override the global setting of the $.ajaxSetup() method.

4.async

Requires Boolean type parameters, the default setting is true, and all requests are asynchronous requests. If synchronous requests are required, set this option to false. Note that a synchronous request will lock the browser, and the user must wait for the request to complete before other operations can be performed.

5.cache

Requires parameters of Boolean type, the default is true (when dataType is Script, the default is false), set false will not load the request information from the browser cache.

6.data

Requires parameters of type Object or String, data sent to the server. If it is not a string, it will be automatically converted to string format. The get request will be appended to the URL. To prevent this automatic conversion, check the processData option. The object must be in key/value format, for example {foo1:"bar1",foo2:"bar2"} is converted to &foo1=bar1&foo2=bar2. If it is an array, JQuery will automatically assign the same name to different values. For example, {foo:["bar1","bar2"]} is converted to &foo=bar1&foo=bar2.

7.dataType

requires parameters of String type and expects the

data type returned by the server. If not specified, jQuery will automatically return responseXML or responseText based on the mine information of the HTTP package and pass it as a callback function parameter. The available types are as follows:

XML: Returns an XML document that can be processed with jQuery.

HTML: Returns plain text HTML information; the included script tag will be executed when inserted into the DOM.

Script: Returns plain text javascript code. Results are not automatically cached unless the cache parameter is set. Note that when making remote requests (not under the same domain), all post requests will be converted into get requests.

json: Returns JSON data.

jsonp: JSON format. When calling a function using JSONP format, such as myurl?callback=?, JQuery will automatically replace the last "?" with the correct function name to execute the callback function.

Text: Returns a plain text string.

8.beforeSend

requires parameters of Function type. You can modify the function of the XMLHttpRequest object before sending the request, such as adding a custom HTTP header. If false is returned in beforeSend, this ajax request can be canceled. The XMLHttpRequest object is the only parameter.

function(XMLHttpRequest){
    this;//调用本次ajax请求时传递的options参数
  }

9.complete

requires a parameter of Function type, a callback function called after the request is completed (called whether the request succeeds or fails) . Parameters: XMLHttpRequest object and a string describing the successful request type.

  function(XMLHttpRequest,textStatus){
    this; //调用本次ajax请求时传递的options参数
  }

10.success

Requires parameters of Function type. The callback function called after the request is successful has two parameters.

  (1) Data returned by the server and processed according to the dataType parameter.

 (2) A string describing the status.

  function(data,textStatus){
    //data可能是xmlDoc、jsonObj、html、text等
    this; //调用本次ajax请求时传递的options参数
  }

11.error

requires a parameter of Function type, which is the function to be called when the request fails. This function has three parameters, namely XMLHttpRequest object, error message, and captured error object (optional). The ajax event function is as follows:

  function(XMLHttpRequest,textStatus,errorThrown){
    //通常情况下textStatus和errorThrown只有其中一个包含信息
    this; //调用本次ajax请求时传递的options参数
  }

12.contentType

requires parameters of String type when sending information to the server. The content encoding type defaults to "application/x-www-form-urlencoded". This default value is suitable for most applications.

13.dataFilter

requires parameters of Function type, a function that preprocesses the original data returned by Ajax. Provide two parameters: data and type. data is the original data returned by Ajax, and type is the dataTYpe parameter provided when calling jQuery.ajax. The value returned by the function will be further processed by jQuery.

  function(data,type){
    //返回处理后的数据
    return data;
  }

14.global

Requires parameters of Boolean type, defaults to true. Indicates whether to trigger the global ajax event. Setting to false will not trigger global ajax events, ajaxStart and ajaxStop can be used to control various ajax events.

15.ifModified

Requires parameters of Boolean type, defaults to false. Only get new data when server data changes. The basis for determining server data changes is the Last-Modified header information. The default value is false, which means header information is ignored.

16.jsonp

requires parameters of String type and rewrites the name of the callback function in a jsonp request. This value is used to replace the "callback" part of the URL parameter in a GET or POST request such as "callback=?". For example, {jsonp:'onJsonPLoad'} will cause "onJsonPLoad=?" to be passed to the server.

17.username

is required to be a parameter of String type, used to respond to the user of the HTTP access authentication request.

18.password

is required to be a String type parameter, which is the password used to respond to the HTTP access authentication request.

19.processData

Requires a Boolean type parameter, and the default is true. By default, the data sent will be converted to objects (technically not strings) to match the default content type "application/x-www-form-urlencoded". If you want to send DOM tree information or other information that you do not want to convert, please set it to false.

20.scriptCharset

requires parameters of String type. Only when the request dataType is "jsonp" or "script", and type It will be used to force the character set (charset) to be modified only when it is GET. Usually used when the local and remote content encodings are different.

Case code:

$(function(){
 $('#send').click(function(){
  $.ajax({
  type: "GET",
  url: "test.json",
  data: {username:$("#username").val(), content:$("#content").val()},
  dataType: "json",
  success: function(data){
    $('#resText').empty(); //清空resText里面的所有内容
    var html = '';
    $.each(data, function(commentIndex, comment){
    html += '<p></p><h6>' + comment['username']
      + ':</h6><p></p>';
    });
    $('#resText').html(html);
   }
  });
 });
});

Knowledge link:

1. $.each() function: $.each( ) function is different from the each() method of jQuery object. It is a global function and does not operate jQuery object. This function receives two parameters, the first parameter is an array or object, and the second parameter is a callback function. The callback function has two parameters: the first parameter is the index of the array or the member of the object, and the second parameter is the corresponding variable or content.

  $.each(data,function(commentIndex,comment){
  //doSomething;
 })

2、ajaxStart()与ajaxStop():当Ajax请求开始时,会触发ajaxStart()方法的回调函数。当Ajax请求结束时,会触发ajaxStop()方法的回调函数。这些方法都是全局的方法,因此无论创建它们的代码位于何处,只要有Ajax请求发生时,就会触发它们。

有时候页面需要加载一些图片,可能速度回比较慢,如果在加载过程中,不给用户提供一些提示和反馈信息,很容易让用户误认为按钮单击无用,使用户对网站失去信息。

此时,我们就需要为网页添加一个提示信息,常用的提示信息是“加载中...”,代码如下:

<p>加载中...</p>

当Ajax请求开始时,将此元素显示,用来提示用户Ajax请求正在进行;当Ajax请求结束后,将此元素隐藏。代码如下:

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

好了,下面再给大家分享一个案例代码:

$(function(){
 $('#send').click(function(){
  $.ajax({
  type: "GET",
  url: "test.json",
  data: {username:$("#username").val(), content:$("#content").val()},
  dataType: "json",
  success: function(data){
    $('#resText').empty(); //清空resText里面的所有内容
    var html = ''; 
    $.each(data, function(commentIndex, comment){
    html += '<p></p><h6>' + comment['username']
      + ':</h6><p></p>';
    });
    $('#resText').html(html);
   }
  });
 });
});

end,代码到此结束。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

ajax怎么实现网络请求的封装

Ajax和JavaScript使用的区别

The above is the detailed content of How to use the parameters of the $.Ajax() method. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools