Home  >  Article  >  Web Front-end  >  what is ajax function

what is ajax function

藏色散人
藏色散人Original
2021-12-17 11:24:352553browse

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。这相当于设置3f1c4e4b6b16bbbd69b2ee476dc4f83a标签的charset属性。通常只在当前页面和远程数据的内容编码不同时使用。

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