search
HomeWeb Front-endFront-end Q&Awhat is ajax function

what is ajax function

Dec 17, 2021 am 11:24 AM

The ajax function refers to the jQuery.ajax() function, which is used to load remote data through background HTTP requests. It is an AJAX technology implementation encapsulated by jQuery. Through this function, we can obtain remote data without refreshing the current page. data on the server.

what is ajax function

The operating environment of this article: Windows 7 system, jquery version 3.2.1, Dell G3 computer.

What is the ajax function?

jQuery.ajax() function detailed explanation

jQuery.ajax() function is used to load through background HTTP requests Remote data.

jQuery.ajax() The function is an implementation of AJAX technology encapsulated by jQuery. Through this function, we can obtain data on the remote server without refreshing the current page.

jQuery.ajax() The function is the underlying AJAX implementation of jQuery. jQuery.get(), jQuery.post(), load(), jQuery.getJSON(), jQuery.getScript() and other functions are all simplified forms of this function (they all call this function, but the parameter settings are different or have some differences). omitted).

This function belongs to the global jQuery object (can also be understood as a static function).

Parameters

Please find the corresponding parameters according to the parameter names defined in the previous syntax section.

Parameters Description
url String type URL request string.
settings Optional/Object type An Object object, each attribute of which is used to specify additional parameter settings required to send a request .

Parameterssettings is an object, jQuery.ajax() can identify the following properties of the object (they are all optional):

accepts --- ObjectType

Default value: Depends At dataType attribute.

The content type request header sent is used to tell the server what type of response the browser can receive from the server.

async --- Boolean type

Default value: true.

Indicates whether it is an asynchronous request. Synchronous requests lock the browser until the remote data is obtained and no other operations can be performed.

beforeSend---Function type

Specify what needs to be executed before the request is sent Callback. This function also has two parameters: one is the jqXHR object, and the other is the current settings object. This is an Ajax event. If the function returns false, this ajax request will be cancelled.

cache---Boolean type

Default value: true(When dataType is 'script' or 'jsonp', the default is false).

Indicates whether to cache URL requests. If set to false it will force the browser not to cache the current URL request. This parameter is only valid for HEAD and GET requests (POST requests themselves will not be cached).

complete---Function/Array type

Specified requestComplete The callback function that needs to be executed after (regardless of success or failure). This function also has two parameters: one is the jqXHR object, and the other is a string representing the request status ('success', 'notmodified', 'error', 'timeout', 'abort' or 'parsererror '). This is an Ajax event.

Starting from jQuery 1.5, the attribute value can be multiple functions in the form of array, and each function will be executed by a callback.

contents---Object Type1.5 New

An object paired with "{string:regular expression}" to determine how jQuery will parse the response, given its content type.

contentType---String Type

Default value: 'application/x- www-form-urlencoded; charset=UTF-8'.

Send data to the server using the specified content encoding type. The W3C's XMLHttpRequest specification stipulates that the charset is always UTF-8. If you change it to another character set, you cannot force the browser to change the character encoding.

context---Object type

Used to set Ajax related callback functions Context object (that is, the this pointer within the function).

converters --- Object Type1.5 New

Default value: {'* text': window.String, 'text html': true, 'text json': jQuery.parseJSON, 'text <span id="9_nwp">xml': jQuery.parseXML}</span>.

A data type converter. The value of each converter is a function that returns the converted value of the response.

crossDomain---Boolean Type1.5 New

Default value: Same-domain request is false, cross-domain request is true.

Indicates whether it is a cross-domain request. If you want to force cross-domain requests within the same domain (as in JSONP form), set this to true. This allows server-side redirection to another domain, for example.

data---Any type of data

sent to the server will be automatically forwarded is of string type. If it is a GET request, it will be appended to the URL.

dataFilter---Function type

Specifies the callback for processing the raw data of the response function. This function also has two parameters: one is a string representing the original data of the response, and the other is the <span id="8_nwp">dataType</span> attribute string.

dataType---String type

Default value: jQuery smart guess, guess Scope (xml, json, script or html)

Specifies the data type returned. The attribute value can be:

  • 'xml': Returns an XML document that can be processed using jQuery.
  • 'html': Returns an HTML string.
  • 'script': Returns JavaScript code. Results are not cached automatically. Unless the cache parameter is set. Note: When making remote requests (not under the same domain), all POST requests will be converted into GET requests. (Because the DOM script tag will be used to load)
  • 'json': Returns JSON data. JSON data will be parsed using strict syntax (attribute names must be double quoted, and all strings must be double quoted), and an error will be thrown if parsing fails. Starting with jQuery 1.9, responses with empty content will return null or {}.
  • 'jsonp': JSONP format. When calling a function using JSONP format, such as "url?callback=?", jQuery will automatically replace the second ? with the correct function name to execute the callback function.
  • 'text': Returns a plain text string.

error---Function/Array type

Specify the callback function to be executed when the request fails. This function has 3 parameters: jqXHR object, request status string (null, 'timeout', 'error', 'abort' and 'parsererror'), error message string (text description part of the response status, such as 'Not Found' ' or 'Internal Server Error'). This is an Ajax event. Cross-domain scripts and cross-domain JSONP requests will not call this function.

Starting from jQuery 1.5, the attribute value can be multiple functions in the form of array , each function will be executed by a callback.

global---Boolean type

Default value: true.

Indicates whether to trigger the global Ajax event. Setting this value to false will prevent global event handlers from being triggered, such as ajaxStart() and ajaxStop(). It can be used to control various Ajax events.

headers---Object Type1.5 New

default value:{}.

Specify additional request header information in object form. The request header X-Requested-With: XMLHttpRequest will always be added, but you can also modify the default XMLHttpRequest value here. The value in headers can override the request header set in the beforeSend callback function (meaning beforeSend is called first).

$.ajax({
    url: "my.php" ,
    headers: {        "Referer": "http://www.365mini.com" // 有些浏览器不允许修改该请求头
        ,"User-Agent": "newLine" // 有些浏览器不允许修改该请求头
        ,"X-Power": "newLine"
        ,"Accept-Language": "en-US"
    }
});

ifModified---Boolean type

Default value: false .

Allows the current request to obtain new data only when the server data changes (if it has not changed, the browser obtains the data from the cache). It uses HTTP header information Last-Modified to determine. Starting with jQuery 1.4, it also checks the server-specified 'etag' to determine whether the data has been modified.

isLocal---Boolean type1.5.1 Newly added

Default: Depends on the current location protocol.

允许将当前环境视作"本地",(例如文件系统),即使默认情况下jQuery不会如此识别它。目前,以下协议将被视作本地:file*-extensionwidget

jsonp---String类型

重写JSONP请求的回调函数名称。该值用于替代"url?callback=?"中的"callback"部分。

jsonpCallback---String/Function类型

为JSONP请求指定一个回调函数名。这个值将用来取代jQuery自动生成的随机函数名。

从jQuery 1.5开始,你也可以指定一个函数来返回所需的函数名称。

mimeType---String类型1.5.1 新增

一个mime类型用来覆盖XHR的mime类型。

password---String类型

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

processData---Boolean类型

默认值:true

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

scriptCharset---String类型

设置该请求加载的脚本文件的字符集。只有当请求时dataType为"jsonp"或"script",并且type是"GET"才会用于强制修改charset。这相当于设置<script>标签的charset属性。通常只在当前页面和远程数据的内容编码不同时使用。</script>

statusCode---Object类型1.5 新增

默认值: {}

一组数值的HTTP代码和函数构成的对象,当响应时调用了相应的代码。例如:

$.ajax({
    url: a_not_found_url ,    
    // 当响应对应的状态码时,执行对应的回调函数    
    statusCode: {        404: function() {
            alert( "找不到页面" );
        },        200: function(){
            alert("请求成功");
        }
    }
});

success---Function/Array类型

指定请求成功后执行的回调函数。该函数有3个参数:请求返回的数据、响应状态字符串、jqXHR对象。

从jQuery 1.5开始,该属性值可以是数组形式的多个函数,每个函数都将被回调执行。

timeout---Number类型

设置请求超时的毫秒值。

traditional---Boolean类型

如果你希望使用传统方式来序列化参数,将该属性设为true

type---String类型

默认值:"GET"。

请求类型,可以为'POST'或'GET'。注意:你也可以在此处使用诸如'PUT'、'DELETE'等其他请求类型,但它们不被所有浏览器支持。

url --- String类型

默认值:当前页面URL。

请求的目标URL。

username --- String类型

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

xhr --- Function类型

默认值:在IE下是ActiveXObject(如果可用),在其他浏览器中是XMLHttpRequest

一个用于创建并返回XMLHttpRequest对象的回调函数。你可以重写该属性以提供自己的XHR实现,或增强其功能。

xhrFieldsObject类型1.5.1 新增

一个具有多个"字段名称-字段值"对的对象,用于对本地XHR对象进行设置。一对「文件名-文件值」在本机设置XHR对象。例如,如果需要,你可以用它来为跨域请求设置XHR对象的withCredentials属性为true

$.ajax({
   url: a_cross_domain_url,   // 将XHR对象的withCredentials设为true   xhrFields: {
      withCredentials: true
   }
});

注意:
1、如果你的所有AJAX请求都需要设置settings中某些参数,你可以使用jQuery.ajaxSetup()函数进行全局设置,而无需在每次执行jQuery.ajax()时分别设置。
2、在jQuery 1.4(含)之前,选项参数completesucceserrorAjax事件的回调函数的第3个参数不是经过jQuery封装的jqXHR对象,而是原生的XMLHttpRequest对象。

返回值

jQuery.<span id="19_nwp">ajax()</span>函数的返回值为jqXHR类型,返回当前该请求的jqHXR对象(jQuery 1.4及以前版本返回的是原生的XMLHttpRequest对象)。

示例&说明

如果没有给jQuery.ajax()指定任何参数,则默认请求当前页面,并且不对返回数据进行处理。

jQuery.ajax()函数的settings对象中,常用的属性有:url、type、async、data、dataType、success、error、complete、beforeSend、timeout等。

请参考下面这段初始HTML代码:

<div id="content"></div>

以下是与jQuery.ajax()函数相关的jQuery示例代码,以演示jQuery.ajax()函数的具体用法:

(演示页面只有第一个ajax()函数,其他代码请自行复制到演示页面分别执行)

$.ajax({
     url: "jquery_ajax.php"
    , type: "POST"
    , data: "name=codeplayer&age=18"
    , success: function( data, textStatus, jqXHR ){
        // data 是返回的数据
        // textStatus 可能为"success"、"notmodified"等
        // jqXHR 是经过jQuery封装的XMLHttpRequest对象
        alert("返回的数据" + data);
    }
});


$.ajax({
     url: "jquery_ajax.php?page=1&id=3"
    , type: "POST"
    // jQuery会自动将对象数据转换为 "name=codeplayer&age=18&uid=1&uid=2&uid=3"
    , data: { name:"codeplayer", age:18, uid: [1, 2, 3] }
    // 请求成功时执行
    , success: function( data, textStatus, jqXHR ){
        alert("返回的数据" + data);
    }
    // 请求失败时执行
    , error: function(jqXHR, textStatus, errorMsg){
        // jqXHR 是经过jQuery封装的XMLHttpRequest对象
        // textStatus 可能为: null、"timeout"、"error"、"abort"或"parsererror"
        // errorMsg 可能为: "Not Found"、"Internal Server Error"等
        alert("请求失败:" + errorMsg);
    }
});


// 将url单独提取出来作为第一个参数(jQuery 1.5+才支持)
$.ajax("jquery_ajax.php?action=type&id=3", {
     dataType: "json" // 返回JSON格式的数据
    , success: function( data, textStatus, jqXHR ){
        // 假设返回的字符串数据为{ "name": "CodePlayer", age: 20 }
        // jQuery已帮我们将该JSON字符串转换为对应的JS对象,可以直接使用
        alert( data.name ); // CodePlayer
    }   
});


$.ajax( {
    // 注意这里有个参数callback=?
     url: "http://cross-domain/jquery_ajax.php?name=Jim&callback=?&age=21"
    , async: false // 同步请求,发送请求后浏览器将被锁定,只有等到该请求完成(无论成功或失败)后,用户才能操作,js代码才会继续执行
    , dataType: "jsonp" // 返回JSON格式的数据
    , success: function( data, textStatus, jqXHR ){
        // 假设返回的字符串数据为{ "site_name": "CodePlayer", "site_desc": "专注于编程开发技术分享" }
        // jQuery已帮我们将该JSON字符串转换为对应的JS对象,可以直接使用
        alert( data.site_desc ); // 专注于编程开发技术分享
    }   
});


$.ajax( {
    // 加载指定的js文件到当前文档中
     url: "http://code.jquery.com/jquery-1.8.3.min.js"
    , dataType: "script"
});

推荐学习:《ajax视频教程

The above is the detailed content of what is ajax function. 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
React: The Foundation for Modern Frontend DevelopmentReact: The Foundation for Modern Frontend DevelopmentApr 19, 2025 am 12:23 AM

React is a JavaScript library for building modern front-end applications. 1. It uses componentized and virtual DOM to optimize performance. 2. Components use JSX to define, state and attributes to manage data. 3. Hooks simplify life cycle management. 4. Use ContextAPI to manage global status. 5. Common errors require debugging status updates and life cycles. 6. Optimization techniques include Memoization, code splitting and virtual scrolling.

The Future of React: Trends and Innovations in Web DevelopmentThe Future of React: Trends and Innovations in Web DevelopmentApr 19, 2025 am 12:22 AM

React's future will focus on the ultimate in component development, performance optimization and deep integration with other technology stacks. 1) React will further simplify the creation and management of components and promote the ultimate in component development. 2) Performance optimization will become the focus, especially in large applications. 3) React will be deeply integrated with technologies such as GraphQL and TypeScript to improve the development experience.

React: A Powerful Tool for Building UI ComponentsReact: A Powerful Tool for Building UI ComponentsApr 19, 2025 am 12:22 AM

React is a JavaScript library for building user interfaces. Its core idea is to build UI through componentization. 1. Components are the basic unit of React, encapsulating UI logic and styles. 2. Virtual DOM and state management are the key to component work, and state is updated through setState. 3. The life cycle includes three stages: mount, update and uninstall. The performance can be optimized using reasonably. 4. Use useState and ContextAPI to manage state, improve component reusability and global state management. 5. Common errors include improper status updates and performance issues, which can be debugged through ReactDevTools. 6. Performance optimization suggestions include using memo, avoiding unnecessary re-rendering, and using us

Using React with HTML: Rendering Components and DataUsing React with HTML: Rendering Components and DataApr 19, 2025 am 12:19 AM

Using HTML to render components and data in React can be achieved through the following steps: Using JSX syntax: React uses JSX syntax to embed HTML structures into JavaScript code, and operates the DOM after compilation. Components are combined with HTML: React components pass data through props and dynamically generate HTML content, such as. Data flow management: React's data flow is one-way, passed from the parent component to the child component, ensuring that the data flow is controllable, such as App components passing name to Greeting. Basic usage example: Use map function to render a list, you need to add a key attribute, such as rendering a fruit list. Advanced usage example: Use the useState hook to manage state and implement dynamics

React's Purpose: Building Single-Page Applications (SPAs)React's Purpose: Building Single-Page Applications (SPAs)Apr 19, 2025 am 12:06 AM

React is the preferred tool for building single-page applications (SPAs) because it provides efficient and flexible ways to build user interfaces. 1) Component development: Split complex UI into independent and reusable parts to improve maintainability and reusability. 2) Virtual DOM: Optimize rendering performance by comparing the differences between virtual DOM and actual DOM. 3) State management: manage data flow through state and attributes to ensure data consistency and predictability.

React: The Power of a JavaScript Library for Web DevelopmentReact: The Power of a JavaScript Library for Web DevelopmentApr 18, 2025 am 12:25 AM

React is a JavaScript library developed by Meta for building user interfaces, with its core being component development and virtual DOM technology. 1. Component and state management: React manages state through components (functions or classes) and Hooks (such as useState), improving code reusability and maintenance. 2. Virtual DOM and performance optimization: Through virtual DOM, React efficiently updates the real DOM to improve performance. 3. Life cycle and Hooks: Hooks (such as useEffect) allow function components to manage life cycles and perform side-effect operations. 4. Usage example: From basic HelloWorld components to advanced global state management (useContext and

React's Ecosystem: Libraries, Tools, and Best PracticesReact's Ecosystem: Libraries, Tools, and Best PracticesApr 18, 2025 am 12:23 AM

The React ecosystem includes state management libraries (such as Redux), routing libraries (such as ReactRouter), UI component libraries (such as Material-UI), testing tools (such as Jest), and building tools (such as Webpack). These tools work together to help developers develop and maintain applications efficiently, improve code quality and development efficiency.

React and Frontend Development: A Comprehensive OverviewReact and Frontend Development: A Comprehensive OverviewApr 18, 2025 am 12:23 AM

React is a JavaScript library developed by Facebook for building user interfaces. 1. It adopts componentized and virtual DOM technology to improve the efficiency and performance of UI development. 2. The core concepts of React include componentization, state management (such as useState and useEffect) and the working principle of virtual DOM. 3. In practical applications, React supports from basic component rendering to advanced asynchronous data processing. 4. Common errors such as forgetting to add key attributes or incorrect status updates can be debugged through ReactDevTools and logs. 5. Performance optimization and best practices include using React.memo, code segmentation and keeping code readable and maintaining dependability

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.