About the differences and use of $.get (), $.post (), $.ajax () in jquery

Source: Internet
Author: User
Tags http post

  

First, these three methods are the type of request that the Ajax method requires to exchange data with the server.

First, $.get ()

The $.get () method loads data from the server using an HTTP GET request.

Usage format: $.get (Url,[data],[callback])

Description: URL is the request address,

Data is the list of requests ( optional ), and the parameters to be passed are written in the URL .

Callback is the callback function after the successful request, the function accepts two parameters, the first is the data returned by the server, the second parameter is the state of the server, is an optional parameter .

(where the format of the server return data is actually a string situation, not the JSON data format we want, this reference is just for comparison purposes.) )

1 $ ("button"). Click (function() {2 $.get ("url",function(data, Status) {3 alert ("Data:" + Data + "Nstatus:" + status); 4 }); 5   

Official syntax: $.get (url,data,function(DATA,STATUS,XHR), DataType)

Parameters Description
Url Necessary. Specify the URL that you want to request.
Data Optional. Specifies the data that is sent to the server along with the request.
function (DATA,STATUS,XHR) Optional. Specifies the function to run when the request succeeds.
Additional parameters:
  • Data-contains results from the request
  • Status-contains the requested State ("Success", "Notmodified", "Error", "Timeout", "ParserError")
  • xhr -Contains XMLHttpRequest objects
DataType Optional. Specifies the data type of the expected server response.
By default, JQuery will be smart to judge.
Possible types:
  • "XML"-an XML document
  • "HTML"-HTML as plain text
  • "Text"-Plain text string
  • "Script"-Runs the response in JavaScript and returns it as plain text
  • "JSON"-runs the response in JSON and returns it as a JavaScript object
  • "Jsonp"-load a JSON block with Jsonp and add a "? callback=?" To the URL to specify the callback

Second, $.post ()

The $.post () method loads data from the server using an HTTP POST request.

Official syntax:   $ (selector). Post (Url,data, function (DATA,STATUS,XHR), dataType)  

parameters description
url required. Specifies which URL to send the request to.
data Optional. Specifies the data that is sent to the server along with the request.
function (data,status,xhr) Optional. Specifies the function to run when the request succeeds.
Additional parameters:
  • Data -contains result data from the request
  • status -contains the status of the request ("Success", "notmodified", "Error", "Timeout", "ParserError")
  • xhr -Include XMLHttpRequest object
Em>datatype Optional. Specifies the data type of the expected server response.
By default, JQuery will be smart to judge.
Possible types:
  • "xml"-an XML document
  • "HTML"-HTML as Plain text
  • "text"-Plain text string
  • "s Cript "-Runs the response in JavaScript and returns
  • " JSON "in plain text-runs the response in JSON and returns
  • " Jsonp "with a JavaScript object-loaded with JSONP A JSON block that will add a "? callback=?" To the URL to specify the callback

This function is similar to the $.get () parameter, has a type parameter, type is the data type returned , can be Html,xml,json, etc. If we set this parameter to: JSON, then the returned format is in JSON format, and if it is not set, it is the same as the format returned by $.get (), which is a string.

$.post ("Emp.do?p=getallemp", {id:deptid,x:math.random ()},function(data) {            var arry = eval ("(" +data+ ")"); // go to quotation marks, programming JSON string to the JSON type array, or you can add a parameter "JSON" after the $.post function to specify that the data received is a JSON-type             for (var i=0;i<arry.length;i++) {                varnew  Option (Arry[i].empname, ARRY[I].EMPID);                document.getElementById ("emp"). Options.add (OP);            }        });

SAN, $.ajax (Opiton)

  Compared to the above two, this can perform precise demand control.

The Ajax () method is used to perform Ajax (asynchronous HTTP) requests.

All JQuery Ajax methods use the Ajax () method. This method is typically used for requests that other methods cannot complete .

Official syntax: $.ajax ({name:value, Name:value, ...})

the list of parameters that may appear in parentheses is as follows: (more important and common already marked red)

name Value/Description
Async A Boolean value that indicates whether the request is processed asynchronously. The default is true.
Beforesend (xhr) The function that is run before the request is sent.
Cache A Boolean value that indicates whether the browser caches the requested page. The default is true.
Complete (xhr,status) A function that runs when the request completes (called after the request succeeds or fails, that is, after the success and the error function).
ContentType The type of content to use when sending data to the server. The default is: "Application/x-www-form-urlencoded".
Context Specifies the "This" value for all AJAX-related callback functions.
Data Specifies the data to be sent to the server.
Datafilter (data,type) A function for handling XMLHttpRequest raw response data.
DataType The data type of the expected server response.
Error (xhr,status,error) The function to run if the request fails.
Global A Boolean value that specifies whether the global AJAX event handler is triggered for the request. The default is true.
Ifmodified Boolean value that specifies whether the request succeeds only if the response has changed since the last request. The default is False.
Jsonp A string that overrides the callback function in a JSONP.
Jsonpcallback Specifies the name of the callback function in a JSONP.
Password Specifies the password that is used in HTTP access authentication requests.
ProcessData A Boolean value that specifies whether the data sent through the request is converted to a query string. The default is true.
Scriptcharset Specifies the requested character set.
Success (result,status,xhr) The function that is run when the request succeeds.
Timeout Sets the local request time-out (in milliseconds).
Traditional A Boolean value that specifies whether to use the traditional style of parameter serialization.
Type Specifies the type of request (GET or POST).
Url Specifies the URL to send the request to. The default is the current page.
Username Specifies the user name to use in HTTP access authentication requests.
Xhr The function used to create the XMLHttpRequest object.

Example:

1 //querying data by ID2 $.ajax ({3Type: "POST",//Request Type4URL: "Your URL address", 5DataType: "JSON",//data types returned by the server6Asyncfalse,//is synchronized7data:{//It is important to note that this data is passed as a parameter to the background, because it is post, so you can define multiple8"id": ID9         //" name": "Youname",//note, here is just a demonstration, preceded by a variable name, followed by a value to be passedTen         //"Age ": "Youage", One         //" Sex": "Youage", A         //"Other" : " Other" -         }, -Successfunction(data) {//callback result, if successful the         if(Data.status = = 0) {//Judging Status Codes -             //Refresh -$ ("#easyuiDatagrid"). DataGrid ("Reload")); -         } +     }, -Failurefunction(Result) { +Parent.$.messager.show ({title: "Hint", msg: "Failed, please contact administrator", timeout:3000}); A         } at});


Reference:

$.ajax () parameter detailed description: http://www.cnblogs.com/tylerdonet/p/3520862.html

Three ways to explain the difference in detail: http://www.cnblogs.com/liuling/archive/2013/02/07/sdafsd.html

Links to Ajax method sets: Http://www.runoob.com/jquery/jquery-ref-ajax.html

About the differences and use of $.get (), $.post (), $.ajax () in jquery

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.