search
HomeWeb Front-endFront-end Q&AWhat parameters does the ajax function have?

The parameters of the ajax function are: options, async, cache, contentType, context, data, dataFilter, dataType, error, global, ifModified, jsonp, processData, etc.

What parameters does the ajax function have?

The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.

The ajax() function loads remote data through HTTP requests.

This method is the underlying AJAX implementation of jQuery. For simple and easy-to-use high-level implementations, see $.get, $.post, etc. $.ajax() returns the XMLHttpRequest object it created. In most cases you won't need to manipulate this function directly unless you need to manipulate less commonly used options for more flexibility.

In the simplest case, $.ajax() can be used directly without any parameters.

Note: All options can be set globally through the $.ajaxSetup() function.

Syntax:

jQuery.ajax([settings])
Parameters Description
settings

Optional. A collection of key-value pairs used to configure Ajax requests.

You can set the default value of any option through $.ajaxSetup().

参数:

options

  • 类型:Object

  • 可选。AJAX 请求设置。所有选项都是可选的。

async

  • 类型:Boolean

  • 默认值: true。默认设置下,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为 false。

  • 注意,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。

beforeSend(XHR)

  • 类型:Function

  • 发送请求前可修改 XMLHttpRequest 对象的函数,如添加自定义 HTTP 头。

  • XMLHttpRequest 对象是唯一的参数。

  • 这是一个 Ajax 事件。如果返回 false 可以取消本次 ajax 请求。

cache

  • 类型:Boolean

  • 默认值: true,dataType 为 script 和 jsonp 时默认为 false。设置为 false 将不缓存此页面。

  • jQuery 1.2 新功能。

complete(XHR, TS)

  • 类型:Function

  • 请求完成后回调函数 (请求成功或失败之后均调用)。

  • 参数: XMLHttpRequest 对象和一个描述请求类型的字符串。

  • 这是一个 Ajax 事件。

contentType

  • 类型:String

  • 默认值: "application/x-www-form-urlencoded"。发送信息至服务器时内容编码类型。

  • 默认值适合大多数情况。如果你明确地传递了一个 content-type 给 $.ajax() 那么它必定会发送给服务器(即使没有数据要发送)。

context

  • 类型:Object

  • 这个对象用于设置 Ajax 相关回调函数的上下文。也就是说,让回调函数内 this 指向这个对象(如果不设定这个参数,那么 this 就指向调用本次 AJAX 请求时传递的 options 参数)。比如指定一个 DOM 元素作为 context 参数,这样就设置了 success 回调函数的上下文为这个 DOM 元素。

  • 就像这样:

$.ajax({ url: "test.html", context: document.body, success: function(){
        $(this).addClass("done");
      }});

data

  • 类型:String

  • 发送到服务器的数据。将自动转换为请求字符串格式。GET 请求中将附加在 URL 后。查看 processData 选项说明以禁止此自动转换。必须为 Key/Value 格式。如果为数组,jQuery 将自动为不同值对应同一个名称。如 {foo:["bar1", "bar2"]} 转换为 '&foo=bar1&foo=bar2'。

dataFilter

  • 类型:Function

  • 给 Ajax 返回的原始数据的进行预处理的函数。提供 data 和 type 两个参数:data 是 Ajax 返回的原始数据,type 是调用 jQuery.ajax 时提供的 dataType 参数。函数返回的值将由 jQuery 进一步处理。

dataType

  • 类型:String

  • 预期服务器返回的数据类型。如果不指定,jQuery 将自动根据 HTTP 包 MIME 信息来智能判断,比如 XML MIME 类型就被识别为 XML。在 1.4 中,JSON 就会生成一个 JavaScript 对象,而 script 则会执行这个脚本。随后服务器端返回的数据会根据这个值解析后,传递给回调函数。可用值:

    • "xml": 返回 XML 文档,可用 jQuery 处理。

    • "html": 返回纯文本 HTML 信息;包含的 script 标签会在插入 dom 时执行。

    • "script": 返回纯文本 JavaScript 代码。不会自动缓存结果。除非设置了 "cache" 参数。注意:在远程请求时(不在同一个域下),所有 POST 请求都将转为 GET 请求。(因为将使用 DOM 的 script标签来加载)

    • "json": 返回 JSON 数据 。

    • "jsonp": JSONP 格式。使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数。

    • "text": 返回纯文本字符串

error

  • 类型:Function

  • 默认值: 自动判断 (xml 或 html)。请求失败时调用此函数。

  • 有以下三个参数:XMLHttpRequest 对象、错误信息、(可选)捕获的异常对象。

  • 如果发生了错误,错误信息(第二个参数)除了得到 null 之外,还可能是 "timeout", "error", "notmodified" 和 "parsererror"。

  • 这是一个 Ajax 事件。

global

  • 类型:Boolean

  • 是否触发全局 AJAX 事件。默认值: true。设置为 false 将不会触发全局 AJAX 事件,如 ajaxStart 或 ajaxStop 可用于控制不同的 Ajax 事件。

ifModified

  • 类型:Boolean

  • 仅在服务器数据改变时获取新数据。默认值: false。使用 HTTP 包 Last-Modified 头信息判断。在 jQuery 1.4 中,它也会检查服务器指定的 'etag' 来确定数据没有被修改过。

jsonp

  • 类型:String

  • 在一个 jsonp 请求中重写回调函数的名字。这个值用来替代在 "callback=?" 这种 GET 或 POST 请求中 URL 参数里的 "callback" 部分,比如 {jsonp:'onJsonPLoad'} 会导致将 "onJsonPLoad=?" 传给服务器。

jsonpCallback

  • 类型:String

  • 为 jsonp 请求指定一个回调函数名。这个值将用来取代 jQuery 自动生成的随机函数名。这主要用来让 jQuery 生成度独特的函数名,这样管理请求更容易,也能方便地提供回调函数和错误处理。你也可以在想让浏览器缓存 GET 请求的时候,指定这个回调函数名。

password

  • 类型:String

  • 用于响应 HTTP 访问认证请求的密码

processData

  • 类型:Boolean

  • 默认值: true。默认情况下,通过data选项传递进来的数据,如果是一个对象(技术上讲只要不是字符串),都会处理转化成一个查询字符串,以配合默认内容类型 "application/x-www-form-urlencoded"。如果要发送 DOM 树信息或其它不希望转换的信息,请设置为 false。

scriptCharset

  • 类型:String

  • 只有当请求时 dataType 为 "jsonp" 或 "script",并且 type 是 "GET" 才会用于强制修改 charset。通常只在本地和远程的内容编码不同时使用。

success

  • 类型:Function

  • 请求成功后的回调函数。

  • 参数:由服务器返回,并根据 dataType 参数进行处理后的数据;描述状态的字符串。

  • 这是一个 Ajax 事件。

traditional

  • 类型:Boolean

  • 如果你想要用传统的方式来序列化数据,那么就设置为 true。请参考工具分类下面的 jQuery.param 方法。

timeout

  • 类型:Number

  • 设置请求超时时间(毫秒)。此设置将覆盖全局设置。

type

  • 类型:String

  • 默认值: "GET")。请求方式 ("POST" 或 "GET"), 默认为 "GET"。注意:其它 HTTP 请求方法,如 PUT 和 DELETE 也可以使用,但仅部分浏览器支持。

url

  • 类型:String

  • 默认值: 当前页地址。发送请求的地址。

username

  • 类型:String

  • 用于响应 HTTP 访问认证请求的用户名。

xhr

  • 类型:Function

  • 需要返回一个 XMLHttpRequest 对象。默认在 IE 下是 ActiveXObject 而其他情况下是 XMLHttpRequest 。用于重写或者提供一个增强的 XMLHttpRequest 对象。这个参数在 jQuery 1.3 以前不可用。

案例代码:

$(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 += &#39;<div class="comment"><h6>&#39; + comment[&#39;username&#39;]
                                         + &#39;:</h6><p class="para"&#39; + comment[&#39;content&#39;]
                                         + &#39;</p></div>&#39;;
                         });
                         $(&#39;#resText&#39;).html(html);
                      }
         });
    });
});

【相关教程推荐:AJAX视频教程

The above is the detailed content of What parameters does the ajax function have?. 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
What is useEffect? How do you use it to perform side effects?What is useEffect? How do you use it to perform side effects?Mar 19, 2025 pm 03:58 PM

The article discusses useEffect in React, a hook for managing side effects like data fetching and DOM manipulation in functional components. It explains usage, common side effects, and cleanup to prevent issues like memory leaks.

Explain the concept of lazy loading.Explain the concept of lazy loading.Mar 13, 2025 pm 07:47 PM

Lazy loading delays loading of content until needed, improving web performance and user experience by reducing initial load times and server load.

How does currying work in JavaScript, and what are its benefits?How does currying work in JavaScript, and what are its benefits?Mar 18, 2025 pm 01:45 PM

The article discusses currying in JavaScript, a technique transforming multi-argument functions into single-argument function sequences. It explores currying's implementation, benefits like partial application, and practical uses, enhancing code read

What are higher-order functions in JavaScript, and how can they be used to write more concise and reusable code?What are higher-order functions in JavaScript, and how can they be used to write more concise and reusable code?Mar 18, 2025 pm 01:44 PM

Higher-order functions in JavaScript enhance code conciseness, reusability, modularity, and performance through abstraction, common patterns, and optimization techniques.

How does the React reconciliation algorithm work?How does the React reconciliation algorithm work?Mar 18, 2025 pm 01:58 PM

The article explains React's reconciliation algorithm, which efficiently updates the DOM by comparing Virtual DOM trees. It discusses performance benefits, optimization techniques, and impacts on user experience.Character count: 159

How do you connect React components to the Redux store using connect()?How do you connect React components to the Redux store using connect()?Mar 21, 2025 pm 06:23 PM

Article discusses connecting React components to Redux store using connect(), explaining mapStateToProps, mapDispatchToProps, and performance impacts.

What is useContext? How do you use it to share state between components?What is useContext? How do you use it to share state between components?Mar 19, 2025 pm 03:59 PM

The article explains useContext in React, which simplifies state management by avoiding prop drilling. It discusses benefits like centralized state and performance improvements through reduced re-renders.

How do you prevent default behavior in event handlers?How do you prevent default behavior in event handlers?Mar 19, 2025 pm 04:10 PM

Article discusses preventing default behavior in event handlers using preventDefault() method, its benefits like enhanced user experience, and potential issues like accessibility concerns.

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

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 agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.