Examples of Ajax usages of jquery learning notes _jquery

Source: Internet
Author: User
Tags getscript http post httpcontext script tag serialization string format browser cache


This example describes the Ajax usage of jquery learning notes. Share to everyone for your reference, specific as follows:



One, Ajax request



1, Jquery.ajax (options)



Load remote data through an HTTP request. JQuery bottom AJAX implementation. Simple and easy-to-use high-level implementation see. get,.post.



. Ajax () returns the XMLHttpRequest object that it creates. Most of the time you don't have to manipulate the object directly, but in special cases you can use it to manually terminate the request. Ajax () has only one parameter: The parameter Key/value object, which contains the configuration and callback function information. Detailed parameter options see below.



Note: If you specify the DataType option, make sure that the server returns the correct MIME information (such as the XML return "Text/xml"). The wrong MIME type can cause unpredictable errors.



Note: If datatype is set to script, all post requests will be converted to get requests at remote request (not under the same domain). (because it will be loaded using the DOM's script tag)



In JQuery 1.2, you can load JSON data across domains and use it to set the data type to JSONP. When calling a function using JSONP form, such as "myurl?callback=?" JQuery is automatically replaced? To the correct function name to execute the callback function. When the data type is set to "Jsonp", JQuery automatically invokes the callback function.



return value XMLHttpRequest



Parameters



Options (optional): AJAX request settings. All options are optional.
Options



(1), Async (Boolean): (Default: TRUE)
All requests are asynchronous requests under the default settings. If you need to send a sync request, set this option to false. Note that the synchronization request will lock the browser and the user's other actions must wait for the request to complete before it can be executed.



(2) Beforesend: A function that modifies a XMLHttpRequest object before sending a request, such as adding a custom HTTP header.
The XMLHttpRequest object is the only parameter. This is an Ajax event. If you return False, you can cancel this Ajax request.


function (XMLHttpRequest) {
  this;//The options parameter passed when invoking this Ajax request
}


(3), Cache (Boolean): (Default: True,datatype when script defaults to false)
The new JQuery 1.2 feature, set to False, will not load request information from the browser cache.



(4), complete (function): The callback function (called when the request succeeds or fails) after the request completes.
Parameters: XMLHttpRequest object and a string that describes the type of successful request. This is an Ajax event


function (XMLHttpRequest, textstatus) {
  this;//The options parameter passed when invoking this Ajax request
} 


(5), ContentType (String): (Default: "application/x-www-form-urlencoded") the content encoding type when sending information to the server. Default values are appropriate for most applications.



(6), Data (object,string): Sent to the server. is automatically converted to the request string format. The GET request is appended to the URL. View the ProcessData option description to prevent this automatic conversion.
Must be in the Key/value format. If you are an array, JQuery will automatically correspond to the same name for different values. such as {foo:["bar1", "Bar2"]} is converted to ' &foo=bar1&foo=bar2 '.



(7), Datafilter (function): a function to preprocess the raw data returned by Ajax. Provides data and type two parameters: Data is the original source 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) {
  //preprocessing of raw data returned by AJAX return data
  //back to processed information
} 


(8), DataType (String): (Default value: Intelligent judgment xml or HTML)
The type of data expected to be returned by the server. If not specified, JQuery will automatically return Responsexml or responsetext based on the HTTP packet MIME information and pass as a callback function parameter, available values:



"XML": Returns an XML document that can be processed with jQuery.
HTML: Returns plain text HTML information, and the included script tag executes when the DOM is inserted.
Script: Returns the plain text JavaScript code. Results are not automatically cached. Unless the "cache" parameter is set. Note: On remote requests (not in the same domain), all post requests are converted to get requests. (because it will be loaded using the DOM's script tag)
"JSON": Returns JSON data.
"JSONP": Jsonp format. When calling a function using JSONP form, such as "myurl?callback=?" JQuery is automatically replaced? To the correct function name to execute the callback function.
' Text ': Returns a plain text string



(9), error (Function): (Default: Automatic judgment (XML or HTML)) call time when a request fails. The parameter has the following three: XMLHttpRequest object, error message, optionally caught error object. If an error occurs, the error message (the second argument) may be "timeout", "error", "Notmodified", and "ParserError" in addition to being null. Ajax events.


function (XMLHttpRequest, textstatus, Errorthrown) {
  //usually Textstatus and Errorthrown
  //Only one will contain information this
  ;//Tune Options parameter to be passed when using this Ajax request



(10), Global (Boolean): (default: TRUE) whether the global AJAX event is triggered. Setting to FALSE will not trigger global AJAX events, such as Ajaxstart or ajaxstop, that can be used to control different AJAX events.



(11), Ifmodified (Boolean): (default: false) gets new data only when server data changes. Use HTTP packet last-modified header information to determine.



(12), Jsonp (String): Overrides the name of the callback function in a JSONP request. This value is used to replace the "callback=?" The "callback" section of the URL parameter in this get or POST request, such as {jsonp: ' Onjsonpload '}, will cause the "onjsonpload=?" passed to the server.



(13), Password (String): Password used in response to HTTP access authentication requests



(14), ProcessData (Boolean): (Default: TRUE) by default, the data sent is converted to an object (technically not a string) to match the default content type "application/x-www-form-urlencoded". Set to False if you want to send DOM tree information or other information that you do not want to convert.



(15), Scriptcharset (String): DataType is "JSONP" or "script" only when requested, and type "get" is used to force the modification of CharSet. Typically used when local and remote content encodings are different.



(16), Success (function): callback function after a successful request. Parameters: Data returned by the server, processed according to the datatype parameter, and a string describing the state. Ajax events.


function (data, textstatus) {
  //data may be xmldoc, jsonobj, HTML, text, and so on
  this;//The options parameter passed when invoking this Ajax request
}


(17), timeout (number): Sets the request timeout (milliseconds). This setting overrides the global setting.



(18), type (String): (Default: "Get") Request method ("POST" or "get"), default to "get". Note: Other HTTP request methods, such as put and DELETE, are also available, but only partially supported by browsers.



(19), URL (String): (Default: Current page address) Send the address of the request.



(20), username (String): User name used in response to HTTP access authentication requests



(21), XHR (Function): You need to return a XMLHttpRequest object. The default is ActiveXObject under IE, and in other cases it is xmlhttprequest. Used to override or provide an enhanced XMLHttpRequest object. This parameter is not available until jquery 1.3.



PS: The red mark above is the most commonly used parameter settings for AJAX calls, which can be successfully implemented using these parameters.



Example


//jQTest.js
function jqAjaxTest() {
var jqRequestUrl = "AjaxHandler.ashx";
//1. Load and execute a JS file
$.ajax ({)
Type: "GET",
url: "js/jqLoadJs.js",
dataType: "script"
};
//2. Load the latest version of an HTML page
$.ajax ({)
url: "test.htm",
Cache: false, / / no cache
success: function(html) {
//alert(html);
$("#spanGetHtml").css("display", "block");
$("#spanGetHtml").css("color", "red");
$("#spanGetHtml").append(html);
}
};
//3. Get and parse an XML file (get XML from the server)
$.ajax ({)
Type:'GET',
Datatype: 'XML', / / it can not be written here, but do not write text or HTML
url: jqRequestUrl + "?action=jquerGetXmlRequest",
success: function(xml) {
//Correctly parsing the XML file of the server
$(xml).find("profile").each(function(i) {
Var name = $(this). Children ("username"). Text(); / / get object text
var location = $(this).children("location").text();
alert("Xml at SERVER is gotten by CLIENT:" + name + " is living in " + location);
};
}
error: function(xml) {
alert('An error happend while loading XML document ');
}
};
//4. Send XML data to server (client sends XML to server)
var xmlDocument = "<profile>" +
" <userName>jeff wong</userName>" +
" <location>beijing</location>" +
"</profile>";
$.ajax ({)
url: jqRequestUrl + "?action=jqueryXmlRequest",
Processdata: false, / / set the processdata option to false to prevent automatic data format conversion.
//type: "xml",
cache: false,
Type: "XML",
data: xmlDocument,
success: function(html) {
Alert (HTML); / / pop up prompt
$("#spanResult").css("display", "block");
$("#spanResult").css("color", "red");
$("spanresult"). HTML (HTML); / / assign a value to a span element of the current DOM
}
error: function(oXmlHttpReq, textStatus, errorThrown) {
alert("jquery ajax xml request failed");
$("#spanResult").css("display", "block");
$("#spanResult").css("color", "red");
$("ාspanresult"). HTML ("jQuery Ajax XML request failed"); / / error prompted
}
};
//5. Load data synchronously. Lock the browser when sending the request. Use synchronization when user interaction needs to be locked.
var html = $.ajax({
//No type defaults to get mode
url: jqRequestUrl + "?action=syncRequest",
Async: false
}).responseText;
Alert (HTML);
//6. Explicit get test
$.ajax ({)
Type: "GET",
url: jqRequestUrl + "?action=jquery&amp;userName=" + $("#txtUserName").val(),
cache: false,
success: function(html) {
//Alert (HTML); / / pop up prompt
$("#spanResult").css("display", "block");
$("#spanResult").css("color", "red");
$("spanresult"). HTML (HTML); / / assign a value to a span element of the current DOM
}
error: function(oXmlHttpReq, textStatus, errorThrown) {
alert("jquery ajax request failed");
$("#spanResult").css("display", "block");
$("#spanResult").css("color", "red");
$("ාspanresult"). HTML ("jQuery Ajax request failed"); / / error prompted
}
};
//7. Explicit post test
$.ajax ({)
type: "POST",
url: jqRequestUrl,
data: "action=jquerySaveData&amp;userName=jeffwong&amp;location=beijing",
success: function(html) {
Alert (HTML);
}
};
}
 


Several related documents:



A, processing Ajax request Server file: AJAXHANDLER.ASHX, the corresponding CS file:


Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using System.Web.SessionState;
Using System.Xml; Namespace Myjqtest {public class Ajaxhandler:ihttphandler, irequiressessionstate {///&lt;summary&gt;///
      Reusable///&lt;/summary&gt; public bool IsReusable {get {true;
    } public void ProcessRequest(HttpContext context)
{
AjaxOperations(context);
}
private void AjaxOperations(HttpContext context)
{
string action = context.Request["action"];
if (!string.IsNullOrEmpty(action))
{
switch (action)
{
Default:
Break;
case "jquery":
ProcessJQueryRequest(context);
Break;
case "jquerySaveData":
ProcessJQuerySaveData(context);
Break;
case "syncRequest":
ProcessJQuerySyncRequest(context);
Break;
case "jqueryXmlRequest":
ProcessJQueryXMLRequest(context);
Break;
case "jquerGetXmlRequest":
ProcessJQueryGetXMLRequest(context);
Break;
}
}
}
private void ProcessJQueryRequest(HttpContext context)
{
context.Response.ClearContent();
Context. Response. Contenttype = "text / plain"; / / set output stream type
Context. Response. Cache. Setcacheability (httpcacheability. Nocache); / / no cache
string result = context.Request["userName"].Trim();
context.Response.Write("You have entered a name:" + result);
}
private void ProcessJQuerySaveData(HttpContext context)
{
context.Response.ClearContent();
Context. Response. Contenttype = "text / plain"; / / set output stream type
Context. Response. Cache. Setcacheability (httpcacheability. Nocache); / / no cache
string name = context.Request["userName"].Trim();
string location = context.Request["location"].Trim();
context.Response.Write("Your data have been saved:your name is " + name + ",living in " + location);
}
private void ProcessJQuerySyncRequest(HttpContext context)
{
context.Response.ClearContent();
Context. Response. Contenttype = "text / plain"; / / set output stream type
Context. Response. Cache. Setcacheability (httpcacheability. Nocache); / / no cache
context.Response.Write("Your sync ajax request has been processed.");
}
/// <summary>
///Simple XML request processing (the server obtains XML from the client)
/// </summary>
/// <param name="context"></param>
private void ProcessJQueryXMLRequest(HttpContext context)
{
context.Response.ClearContent();
Context. Response. Cache. Setcacheability (httpcacheability. Nocache); / / no cache
XmlDocument doc = new XmlDocument();
Try
{
Doc. Load (context. Request. InputStream); / / get XML (pay attention to the method of accepting XML data here)
Context. Response. Contenttype = "text / plain"; / / set output stream type
string name = doc.SelectSingleNode("profile/userName").InnerText;
string location = doc.SelectSingleNode("profile/location").InnerText;
context.Response.Write("Your XML data have received,and your name is " + name + ",living in " + location);
}
catch (Exception ex)
{
context.Response.Write("Get xml data failed.");
Throw ex;
}
}
/// <summary>
///Return simple XML (server returns client XML)
/// </summary>
/// <param name="context"></param>
private void ProcessJQueryGetXMLRequest(HttpContext context)
{
context.Response.ClearContent();
Context. Response. Cache. Setcacheability (httpcacheability. Nocache); / / no cache
XmlDocument doc = new XmlDocument();
Try
{
doc.Load(context.Server.MapPath("/jeffWong.xml"));
Context. Response. Contenttype = "text / XML; charset = UTF-8"; / / set the output stream type
context.Response.Write(doc.OuterXml);
}
catch (Exception ex)
{
context.Response.Write("Load xml data failed.");
Throw ex;
}
}
}
}


B, aspx,html and XML files (placed directly under the root directory)



aspx files are Ajax request pages:


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JQuery.aspx.cs" Inherits="MyJqTest.JQuery" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="js/jquery-1.3.1.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<span style="display: none" id="spanGetHtml"></span>
<br / >
Please input a name:<input id="txtUserName" type="text" /><input id="btnJQAjax" type="button"
Value = "jQuery Ajax request" onclick = "jqajaxtest()" / >
<span style="display: none" id="spanResult"></span>
</div>
<script src="js/jQTest.js" type="text/javascript"></script>
</form>
</body>
</html>


HTML is simple:



Test.htm:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
  <title></title>
</head>
<body>
<div>it is a simple ajax test</div>
</body>
</html>





XML file:



Jeffwong.xml:


<?xml version= "1.0" encoding= "Utf-8"?>
<profile>
 <username>jeff wong</username>
 <location>beijing</location>
</profile>


C, JS file (placed in the root directory JS folder)



Jqloadjs.js test Ajax loaded JS file with


Copy Code code as follows:
Alert ("This is a AJAX request script test");





2, Load (Url,[data],[callback])



Loads the remote HTML file code and inserts it into the DOM.



Use the Get method by default-when passing additional parameters is automatically converted to POST mode. In JQuery 1.2, you can specify a selector to filter the loaded HTML document, and only the filtered HTML code will be inserted into the DOM. Syntax is like "URL #some > selector". Please see the example.



return value JQuery



Parameters



URL (String): To be loaded into the HTML Web site.
Map,string: (optional) Key/value data sent to the server. You can also accept a string in jquery 1.3.
Callback (callback): (optional) callback function when successfully loaded.



Example:


function Jqajaxtest () {
  $ ("#spanResult"). Load ("test.htm");
  $ ("#spanResult"). CSS ("Display", "block");
  $ ("#spanResult"). CSS ("Color", "red");



3, Jquery.get (Url,[data],[callback],[type])



Loads information through a remote HTTP GET request.



This is a simple GET request feature to replace the complex. Ajax. Callback functions can be invoked when the request succeeds. If you need to perform a function when an error occurs, use. Ajax.



return value XMLHttpRequest



Parameters



URL (String): URL address of the page to be loaded
Data (MAP): (optional) Key/value parameters to be sent.
Callback (function): (optional) callback function when successfully loaded.
Type (String): (optional) returns the content format, XML, HTML, script, JSON, text, _default.



Example


function Jqajaxtest () {
  var jqrequesturl = "Ajaxhandler.ashx";
  $.get (Jqrequesturl + "? Action=jquery", {userName: "Jeff Wong", Location: "Beijing"}, Jqgetnormalcallback, ' text '); Returns data type
}
function Jqgetnormalcallback (oData) {
  $ ("#spanResult"). HTML (oData);//Here Direct JSON data is bound, The next jquery method will have processing
  $ ("#spanResult"). CSS ("Display", "block");
  $ ("#spanResult"). CSS ("Color", "red");



AJAXHANDLER.ASHX Code:


Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using System.Web.SessionState;
Using System.Xml; Namespace Myjqtest {public class Ajaxhandler:ihttphandler, irequiressessionstate {///&lt;summary&gt;///
      Reusable///&lt;/summary&gt; public bool IsReusable {get {true;
    } public void ProcessRequest (HttpContext context) {ajaxoperations (context); private void Ajaxoperations (HttpContext context) {string action = context.
      Request["Action"]; if (!string.
          IsNullOrEmpty (Action)) {switch (action) {default:break;
            Case "jquery": the Processjqueryrequest (context);
        Break }} private void Processjqueryrequest (HttpContext context) {context.
      Response.clearcontent (); Context. Response.ContentType = "Text/plain"; Sets the output stream type context. Response.cachE.setcacheability (Httpcacheability.nocache); No cache string userName = context. request["UserName"].
      Trim (); String location = Context. request["Location"].
      Trim ();
      String jsonobject = "{\" username\ ": \" "+ UserName +" \ "," location\ ": \" "+ location +" \ "}"; Context.
    Response.Write (Jsonobject);

 }
  }
}


PS: In this case, we return a JSON type of data that is not processed by the client on the JSON type data and is improved in the next method (Jquery.getjson).



4, Jquery.getjson (Url,[data],[callback])



Load JSON data through an HTTP GET request.



In JQuery 1.2, you can load JSON data for other domains, such as "myurl?callback=?", by using a callback function in JSONP form. Will jQuery be replaced automatically? To the correct function name to execute the callback function.
Note: The code after this line will execute before the callback function executes.



return value XMLHttpRequest



Parameters



URL (String): Sends the request address.
Data (MAP): (optional) Key/value parameters to be sent.
Callback (function): (optional) callback function when successfully loaded.



Example


function Jqajaxtest () {
  var jqrequesturl = "Ajaxhandler.ashx";
  Getjson method calls
  $.getjson (Jqrequesturl + "? Action=jquery", {userName: "Jeff Wong", Location: "Beijing"}, Jqgetjsoncallback); Returns the JSON data type
}
//Processing JSON data (OData is a JSON type of data)
function Jqgetjsoncallback (oData) {
  var ojsonstr = "" ;
  Take the data in JSON and present
  ojsonstr = "UserName:" + odata.username + "Location:" + odata.location + "<br/>";
  Show all data in Div
  $ ("#divResult"). HTML (OJSONSTR);
  $ ("#divResult"). CSS ("Display", "block");
  $ ("#divResult"). CSS ("Color", "red");



5, Jquery.getscript (Url,[callback])



Loads and executes a JavaScript file through an HTTP GET request.



Before the JQuery 1.2 version, Getscript can only invoke the same domain JS file. 1.2, you can invoke JavaScript files across domains. Note: Safari 2 or earlier cannot execute scripts synchronously in the global scope. If you add a script by getscript, add the delay function.



return value XMLHttpRequest



Parameters



URL (String): The JS file address is to be loaded.
Callback (function): (optional) After successfully loading the callback function.



Example


function Jqajaxtest () {
  var jsurl = "Js/jqloadjs.js";
  Getscript method calls
  $.getscript (jsurl, jqgetjscallback);
}
OData returns the entire JS path under the JS file content
function Jqgetjscallback (oData) {
  alert (oData);
}


6, Jquery.post (Url,[data],[callback],[type])



Loads information through a remote HTTP POST request.



This is a simple POST request feature to replace complex. Ajax. Callback functions can be invoked when the request succeeds. If you need to perform a function when an error occurs, use. Ajax.



return value XMLHttpRequest



Parameters



URL (String): Sends the request address.
Data (MAP): (optional) Key/value parameters to be sent.
Callback (function): (optional) callback function when sending success.
Type (String): (optional) returns the content format, XML, HTML, script, JSON, text, _default.



Example


function Jqajaxtest () {
  var jqrequesturl = "Ajaxhandler.ashx";
  $.post (Jqrequesturl + "? Action=jquery", {userName: "Jeff Wong", Location: "Beijing"}, Jqpostcallback, "text"); Returns the text data type
}
function Jqpostcallback (oData) {
  //Show all data in Div
  $ ("#divResult"). HTML (oData);
  $ ("#divResult"). CSS ("Display", "block");
  $ ("#divResult"). CSS ("Color", "red");



Second, Ajax events



1, Ajaxcomplete (callback)



Executes the function when the AJAX request completes. Ajax events.



XMLHttpRequest objects and settings are passed as arguments to the callback function.



return value JQuery



Parameters



Callback (function): Pending function



Example


function Jqajaxtest () {
  var jqrequesturl = "Ajaxhandler.ashx";
  $.post (Jqrequesturl + "? Action=jquery", {userName: "Jeff Wong", Location: "Beijing"}, Jqpostcallback, "text"); Returns the text data type
  //ajax execution function
  $ ("#divResult") when the request completes. Ajaxcomplete (function (event, request, Settings) {
    $ (this ). Append ("<br/> request complete.");}
function Jqpostcallback (oData) {
  //display all data in div
  $ ("#divResult"). HTML (oData);
  $ ("#divResult"). CSS ("Display", "block");
  $ ("#divResult"). CSS ("Color", "red");



2, Ajaxerror (callback)



Executes a function when an error occurs on an AJAX request. Ajax events.



XMLHttpRequest objects and settings are passed as arguments to the callback function. The error that is caught can be passed as the last parameter.



return value JQuery



Parameters



Callback (function): Pending function


function (event, XMLHttpRequest, Ajaxoptions, thrownerror) {
   //Thrownerror is passed only when an exception occurs
   ;//listener DOM element}


Example


function Jqajaxtest () {
  var jqrequesturl = "Ajaxhandlers.ashx";//correct filename ajaxhandler.ashx here intentionally writes the error raises the Ajaxerror event
  $.post (Jqrequesturl + "? Action=jquery", {userName: "Jeff Wong", Location: "Beijing"}, Jqpostcallback, "text");
}
executes the function (this paragraph can also be placed within the Jqajaxtest function) $ ("#divResult") when an error occurs in the//ajax request
. Ajaxerror (function (event, request, settings) {
  $ ("#divResult"). CSS ("Display", "block");
  $ ("#divResult"). CSS ("Color", "red");
  $ (this). Append ("<br/> error page:" + settings.url);
});
function Jqpostcallback (oData) {
  //display all data in div
  $ ("#divResult"). HTML (oData);
  $ ("#divResult"). CSS ("Display", "block");
  $ ("#divResult"). CSS ("Color", "red");



3, Ajaxsend (callback)



Executes the function before the AJAX request is sent. Ajax events.



XMLHttpRequest objects and settings are passed as arguments to the callback function.



return value JQuery



Parameters



Callback (function): Pending function



Example


function Jqajaxtest () {
  var jqrequesturl = "Ajaxhandler.ashx"; 
  $.post (Jqrequesturl + "? Action=jquery", {userName: "Jeff Wong", Location: "Beijing"}, Jqpostcallback, "text");
}
//ajax Execute function
$ ("#divResult") before sending request. Ajaxsend (Functions (evt, request, Settings) {
  $ ("#divResult"). CSS (" Display "," block ");
  $ ("#divResult"). CSS ("Color", "red");
  $ (this). Append ("<br/> start Request:" + Settings.url + "<br/>");
});
function Jqpostcallback (oData) {
  //display all data in div
  $ ("#divResult"). Append (oData);
  $ ("#divResult"). CSS ("Display", "block");
  $ ("#divResult"). CSS ("Color", "red");



4, Ajaxstart (callback)



A function is executed when the AJAX request starts. Ajax events.



return value JQuery



Parameters



Callback (function): Pending function



Example


function Jqajaxtest () {
  var jqrequesturl = "Ajaxhandler.ashx"; 
  $.post (Jqrequesturl + "? Action=jquery", {userName: "Jeff Wong", Location: "Beijing"}, Jqpostcallback, "text");
}
//ajax Execution function
$ ("#divResult") at the start of the request. Ajaxstart (Functions () {
  $ ("#divResult"). CSS ("Display", "block");
  $ ("#divResult"). CSS ("Color", "red");
  $ (this). Append ("<br/> request started <br/>");
function Jqpostcallback (oData) {
  //display all data in div
  $ ("#divResult"). Append (oData);
  $ ("#divResult"). CSS ("Display", "block");
  $ ("#divResult"). CSS ("Color", "red");



5, Ajaxstop (callback)



Execute the function at the end of the AJAX request. Ajax events.



return value JQuery



Parameters



Callback (function): Pending function



Example


function Jqajaxtest () {
  var jqrequesturl = "Ajaxhandler.ashx"; 
  $.post (Jqrequesturl + "? Action=jquery", {userName: "Jeff Wong", Location: "Beijing"}, Jqpostcallback, "text");
}
//ajax Execution function
$ ("#divResult") at the start of a request. Ajaxstop (The functions () {
  $ (this). Append ("<br/> request is over <br/ > ");
function Jqpostcallback (oData) {
  //display all data in div
  $ ("#divResult"). Append (oData);
  $ ("#divResult"). CSS ("Display", "block");
  $ ("#divResult"). CSS ("Color", "red");



6, Ajaxsuccess (callback)



Execute function when AJAX request succeeds. Ajax events.



XMLHttpRequest objects and settings are passed as arguments to the callback function.



return value JQuery



Parameters



Callback (function): Pending function



Example


function Jqajaxtest () {
  var jqrequesturl = "Ajaxhandler.ashx"; 
  $.post (Jqrequesturl + "? Action=jquery", {userName: "Jeff Wong", Location: "Beijing"}, Jqpostcallback, "text");
}
Execute function
$ ("#divResult") when//ajax request succeeds. Ajaxsuccess (Functions (evt, request, Settings) {
  $ (this). Append ("< Br/> Request Success <br/> ");
  $ (this). Append (Settings.url);
});
function Jqpostcallback (oData) {
  //display all data in div
  $ ("#divResult"). Append (oData);
  $ ("#divResult"). CSS ("Display", "block");
  $ ("#divResult"). CSS ("Color", "red");



Third, other



1, Jquery.ajaxsetup (options)



Sets the global AJAX default option.



Parameters See ' $.ajax ' description.



return value JQuery



Parameters



Options (optional): Option settings. All setup items are optional settings.



Example


Set AJAX request default address is "AJAXHANDLER.ASHX", prohibit triggering global Ajax event, use POST instead of default get method. Subsequent AJAX requests no longer have any option parameters set. 
$.ajaxsetup ({
  URL: "Ajaxhandler.ashx",
  global:false,
  type: "POST"
});


2, Serialize ()



The serialized form content is a string.



return value JQuery



Parameters



The serialized form content is a string that is used for Ajax requests.



Example


$ (document). Ready (function () {
  var oserializedstr = $ ("form"). Serialize ();//serialization form content is a string
  $ ("#results"). Append ("<tt>" + oserializedstr + "</tt>");
});


Document fragment:


<body>
  <p id= "Results" >
    <b>results: </b>
  </p>
  <form>
  <select name= "single" >
    <option>Single</option>
    <option>Single2</option>
  </select>
  <select name= "multiple" multiple= "multiple" >
    <option selected= "selected" >Multiple</option>
    <option>Multiple2</option>
    <option selected= "selected" > multiple3</option>
  </select><br/>
  <input type= "checkbox" name= "Check" value= " Check1 "/>
  check1
  <input type= checkbox" name= "Check" value= "Check2" checked= "checked"/>
  Check2
  <input type= "Radio" name= "Radio" value= "Radio1" checked= "checked"/> radio1 <input
  Type= "Radio" name= "Radio" value= "Radio2"/>
  radio2
  </form>
  <script src= "Js/jqtest.js" Type= "Text/javascript" ></script>
</body>


3, Serializearray ()



Serializes the contents of the form, returning the JSON data structure.



return value JQuery



Parameters



The serialized form content is JSON and is used for Ajax requests.



Example


$ (document). Ready (function () {
  var fields = $ ("SELECT,: Radio"). Serializearray ();//Serialization Form select and Raido for JSON
  Jquery.each (fields, function (i, field) {
    $ ("#results"). Append (Field.value + "");
  }); 
};


Well, the Ajax on jquery is introduced here, each of the author's examples are tested. jquery encapsulated Ajax functions are really convenient to use, with such a "divine weapon", the future of writing AJAX applications will certainly be more handy.



I hope this article will help you with the jquery program design.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.