Home  >  Article  >  Web Front-end  >  What are the ajax functions?

What are the ajax functions?

青灯夜游
青灯夜游Original
2022-01-17 17:56:262839browse

The ajax functions include: 1. "$(selector).load()", used to load remote data into the selected element; 2. "$.ajax()"; 3. "$ .get()"; 4. "$.post()"; 5. "$.getJSON()"; 6. "$.getScript()".

What are the ajax functions?

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

AJAX request function

##$.getJSON (url,data,callback)Use HTTP GET to load remote JSON data$.getScript(url,callback)Load and execute Remote JavaScript file

(url) The URL (address) of the data being loaded

(data) The key/value object of the data sent to the server

(callback) When the data is loaded, all Function executed

(type) Type of data returned (html, xml, json, jasonp, script, text)

(options) All key/value pair options of the complete AJAX request

1, $.get(url,[data],[callback])

Description: url is the request address, data is the list of requested data, and callback is The callback function after a successful request. This function accepts two parameters. The first parameter is the data returned by the server, and the second parameter is the status of the server. It is an optional parameter.

Among them, the format of the data returned by the server is actually in the form of a string, which is not the json data format we want. It is quoted here just for comparison and explanation

$.get("data.php",$("#firstName.val()"),function(data){
$("#getResponse").html(data); }//返回的data是字符串类型
);

Second, $ .post(url,[data],[callback],[type])

Explanation: This function is similar to the $.get() parameter, with an additional type parameter, type is request The data type can be html, xml, json and other types. If we set this parameter to: json, then the returned format will be json format. If not set, it will The format returned by $.get() is the same, both are string

$.post("data.php",$("#firstName.val()"),function(data){
$("#postResponse").html(data.name);
},"json"//设置了获取数据的类型,所以得到的数据格式为json类型的
);

3, $.ajax(opiton)

Description: $.ajax() This function is powerful and can perform many precise controls on ajax. If you need detailed explanation, please refer to the relevant information

$.ajax({
url: "ajax/ajax_selectPicType.aspx",
data:{Full:"fu"},
type: "POST",
dataType:'json',
success:CallBack,
error:function(er){
BackErr(er);}
});

4, $.getJSON(url,[data],[callback])

$.getJSON("data.php",$("#firstName.val()"),function(jsonData){
$("#getJSONResponse").html(jsonData.id);}//无需设置,直接获取的数据类型为json,所以调用时需要使用jsonData.id方式
);

When Ajax meets jQuery There are more and more AJAX-based applications, and for front-end developers, it is not a pleasant thing to deal directly with the underlying HTTPRequest. Since jQuery is encapsulated JavaScript, I must have considered the issue of AJAX applications. Indeed, if you use jQuery to write AJAX, it will be N times more convenient than writing it directly in JS. (I don’t know how to use jQuery. Will you lose your knowledge of JS...) It is assumed that everyone is already familiar with jQuery syntax, so let's make some summary of some applications of ajax.

Load static page

load( url, [data], [callback] );
url (String) URL address of the requested HTML page
data (Map) (optional parameter) key/value data sent to the server
callback (Callback) (optional parameter) callback function when the request is completed (does not need to be successful)

The load() method can easily load static page content into the specified jQuery object.

$('#ajax-p').load('data.html');

In this way, the content of data.html will be loaded into the DOM object with the ID ajax-p. You can even implement the Ajax operation of loading part of the content by specifying the ID, such as:

$('#ajax-p').load('data.html#my-section');

Implementing the GET and POST methods

get( url, [data], [callback] )
  • url (String) to send the request URL address.

  • data (Map)(optional parameter) 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 Medium

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

Obviously this is a function that specifically implements the GET method, and it is quite simple to use

$.get('login.php', {
   id      : 'Robin',
   password: '123456',
   gate    : 'index'
  }, function(data, status) {
   //data为返回对象,status为请求的状态
   alert(data);
   //此时假设服务器脚本会返回一段文字"你好,Robin!",
那么浏览器就会弹出对话框显示该段文字
   alert(status);
   //结果为success, error等等,但这里是成功时才能运行的函数
  });
post( url, [data], [callback], [type] )
  • url (String) URL address to send the request.

  • data (Map)(optional parameter) The data to be sent to the server, expressed in the form of Key/value pairs

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

  • type (String) (optional Select parameters) Request data type, xml, text, json, etc.

is also a simple function provided by jQuery, its usage

$.post('regsiter.php', {
   id:'Robin',
   password: '123456',
   type:'user'
  },function(data, status) {
   alert(data);
  }, "json");

Event-driven script loading Function: getScript()

getScript( url, [callback] )
  • url (String) Address of JS file to be loaded

  • callback (Function) (optional) Successfully loaded The callback function

#getScript() function can remotely load and execute JavaScript scripts. This function can span Domain loading JS files (magic...?!). The significance of this function is huge Yes, it can greatly reduce the amount of code for the initial loading of the page, because you can load the corresponding JS files based on user interaction instead of loading them all when the page is initialized.

$.getScript('ajaxEvent.js', function() {
   alert("Scripts Loaded!");
   //载入ajaxEvent.js,并且在成功载入后显示对话框提示。
  });

Build a bridge for data communication: getJSON()

getJSON(url,[data],[callback])
  • url (String) Send request address

  • data ( Map) (optional) Key/value parameters to be sent

  • callback (Function) (optional) callback function when loading is successful.

#JSON is an ideal data transmission format that can be well integrated with JavaScript or other host languages. language and can be used directly by JS. Using JSON compared to traditional GET and POST directly send "nude" data, which is more reasonable in structure and safer. As for jQuery's getJSON() function, it only sets the JSON parameters. A simplified version of the ajax() function. This function can also be used across domains and has certain advantages over get() and post(). In addition, this function can be written by writing the request url In the format of "myurl?callback=X", let the program execute the callback function X.

$.getJSON('feed.php',{
   request: images,
   id:      001,
   size:    large
   }, function(json) {
    alert(json.images[0].link);
    //此处json就是远程传回的json对象,假设其格式如下:
    //{'images' : [
    // {link: images/001.jpg, x :100, y : 100},
    // {link: images/002.jpg, x : 200, y 200:}
    //]};
   }
 );

The lower level ajax() function

Although the get() and post() functions are very simple and easy to use, they still cannot achieve some more complex design requirements, such as making different actions at different times when ajax is sent. jQuery provides a more specific function: ajax().

ajax( options )

ajax() provides a large number of parameters, so it can achieve quite complex functions.

Request Description
$(selector).load(url,data,callback) Load remote data into the selected element
$.ajax(options) Load remote data into the XMLHttpRequest object
$.get(url,data,callback,type) Use HTTP GET to load remote data
$.post(url,data,callback,type) Use HTTP POST to load remote data
##ifModifiedBoolean(Default: false) Only get new data when the server data changes .
Parameter name Type Description
url String (default: current page address) The address to send the request.
type String (Default: “GET”) Request method (“POST” or “GET”), default is “GET” .
Note: Other HTTP request methods such as PUT and DELETE can also be used, but are only supported by some browsers.
timeout Number Set the request timeout (milliseconds). This setting overrides the global setting.
async Boolean (Default: true) By default, all requests are asynchronous requests.
If you need to send a synchronous request, please set this option to false.
Note that synchronous requests will lock the browser, and other user operations must wait for the request to be completed before they can be executed.
beforeSend Function Functions that can modify the XMLHttpRequest object before sending the request, such as adding custom HTTP headers.

The XMLHttpRequest object is the only parameter.

function (XMLHttpRequest) { this; // the options for this ajax request } function (XMLHttpRequest) { this; // the options for this ajax request }

cache Boolean (Default: true) jQuery 1.2 new feature, setting it to false will not Load request information in browser cache.
complete Function Callback function after the request is completed (called when the request succeeds or fails).

Parameters: XMLHttpRequest object, success information string.

function (XMLHttpRequest, textStatus) { this; // the options for this ajax request } function (XMLHttpRequest, textStatus) { this; // the options for this ajax request }
contentType String (Default: “application/x-www-form-urlencoded”) Send message to Server content encoding type. The default value is suitable for most applications.
data Object,
String
Data sent to the server. Will be automatically converted to request string format. Appended to the URL in GET requests.
See the processData option description to disable this automatic conversion. Must be in Key/Value format.
If it is an array, jQuery will automatically correspond to the same name for different values.
For example, {foo:["bar1", "bar2"]} is converted to ‘&foo=bar1&foo=bar2′.
dataType String The expected data type returned by the server. If not specified, jQuery will automatically return responseXML or responseText based on the HTTP packet MIME information
and pass it as a callback function parameter. Available values:

"xml": Return an XML document that can be processed by jQuery.

"html": Returns plain text HTML information; contains script elements.

"script": Returns plain text JavaScript code. Results are not cached automatically.

"json": Returns JSON data.

"jsonp": JSONP format. When calling a function using JSONP format,

such as "myurl?callback=?" jQuery will automatically replace ? with the correct function name to execute the callback function.

error Function (Default: automatic judgment (xml or html)) This method will be called when the request fails.

This method has three parameters: XMLHttpRequest object, error message, and (possibly) captured error object.

function (XMLHttpRequest, textStatus, errorThrown) { // Normally only one of textStatus and errorThown has a value this; // the options for this ajax request } function (XMLHttpRequest, textStatus, errorThrown) { // Normally only one of textStatus and errorThown has a value this; // the options for this ajax request }
global Boolean (Default: true) Whether to trigger global AJAX events. Setting to false will not trigger global AJAX events,

such as ajaxStart or ajaxStop. Can be used to control different Ajax events

Use HTTP packet Last-Modified header information to determine.

processData Boolean (默认: true) 默认情况下,发送的数据将被转换为对象(技术上讲并非字符串)

以配合默认内容类型 “application/x-www-form-urlencoded”。

如果要发送 DOM 树信息或其它不希望转换的信息,请设置为 false。

success Function

请求成功后回调函数。这个方法有两个参数:服务器返回数据,返回状态

function (data, textStatus) { // data could be xmlDoc, jsonObj, html, text, etc... this; // the options for this ajax request } function (data, textStatus) { // data could be xmlDoc, jsonObj, html, text, etc... this; // the options for this ajax request }

 你可以指定xml、script、html、json作为其数据类型,可以为beforeSend、error、sucess、complete等状态设置 处理函数,众多其它参数也可以订完完全全定义用户的Ajax体验。下面的例子中,我们用ajax()来调用一个XML文档:

$.ajax({
    url: 'doc.xml',
    type: 'GET',
    dataType: 'xml',
    timeout: 1000,
    error: function(){
        alert('Error loading XML document');
    },
    success: function(xml){
        alert(xml);
  //此处xml就是XML的jQuery对象了,你可以用find()、next()或XPath等方法在里面寻找节点,
和用jQuery操作HTML对象没有区别
    }
});

进一步了解AJAX事件

前面讨论的一些方法都有自己的事件处理机制,从页面整体来说,都只能说是局部函数。jQuery提供了AJAX全局函数的定义,以满足特殊的需求。下面是jQuery提供的所有函数(按照触发顺序排列如下):

  • ajaxStart
    (全局事件) 开始新的Ajax请求,并且此时没有其他ajax请求正在进行

  • beforeSend
    (局部事件) 当一个Ajax请求开始时触发。如果需要,你可以在这里设置XMLHttpRequest对象

  • ajaxSend
    (全局事件) 请求开始前触发的全局事件

  • success
    (局部事件) 请求成功时触发。即服务器没有返回错误,返回的数据也没有错误

  • ajaxSuccess
    全局事件全局的请求成功

  • error
    (局部事件) 仅当发生错误时触发。你无法同时执行success和error两个回调函数

  • ajaxError
    全局事件全局的发生错误时触发

  • complete
    (局部事件) 不管你请求成功还是失败,即便是同步请求,你都能在请求完成时触发这个事件

  • ajaxComplete
    全局事件全局的请求完成时触发

  • ajaxStop
    (全局事件) 当没有Ajax正在进行中的时候,触发
    局部事件在之前的函数中都有介绍,我们主要来看看全局事件。对某个对象进行全局事件监听,那么全局中的AJAX动作,都会对其产生影响。比如,当页面在进行AJAX操作时,ID为”loading”的p就显示出来:

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

全局事件也可以帮助你编写全局的错误相应和成功相应,而不需要为每个AJAX请求独立设置。有必要指出,全局事件的参数是很有用的。除了 ajaxStart、ajaxOptions,其他事件均有event, XMLHttpRequest, ajaxOptions三个参数。第一个参数即事件本身;第二个是XHR对象;第三个是你传递的ajax参数对象。在一个对象里显示全局的AJAX情况:

$("#msg").beforeSend(function(e,xhr,o) {
 $(this).html("正在请求"+o.url);
 }).ajaxSuccess(function(e,xhr,o) {
 $(this).html(o.url+"请求成功");
 }).ajaxError(function(e,xhr,o) {
 $(this).html(o.url+"请求失败");
});

很显然,第三个参数也可以帮助你传递你在AJAX事件里加入的自定义参数。 在单个AJAX请求时,你可以将global的值设为false,以将此请求独立于AJAX的全局事件。

$.ajax({
   url: "request.php",
   global: false,
   // 禁用全局Ajax事件.
 });

如果你想为全局AJAX设置参数,你会用上ajaxSetup()函数。例如,将所有AJAX请求都传递到request.php,;禁用全局方法;强制用POST方法传递:

$.ajaxSetup({
  url: "request.php",
  global: false,
  type: "POST"
});

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

The above is the detailed content of What are the ajax functions?. 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