Introduction to jquery Ajax Walkthrough ($.ajax $.get $.post $.getjson $.getscript)

Source: Internet
Author: User
Tags array definition getscript http post



What is AJAX?



AJAX = asynchronous JavaScript and XML.



AJAX is a technique for creating fast Dynamic Web pages.
AJAX allows Web pages to be updated asynchronously by exchanging small amounts of data in the background with the server. This means it is possible to update part of a Web page without overloading the entire page.



AJAX and JQuery
JQuery provides a rich function (method) library for AJAX development.
With JQuery AJAX, you can request TXT, HTML, XML, or JSON from a remote server using both HTTP GET and HTTP Post.
And you can load the remote data directly into the selected HTML element of the Web page!
Write less and do more
The load function of JQuery is a simple (but powerful) AJAX function. Its syntax is as follows:



$ (selector). Load (Url,data,callback)



Use selector to define the HTML element you want to change, and use the URL parameter to specify the Web address of the data.
Give it a shot yourself.
You need to use the data parameter only if you want to send a message to the server. You need to use the callback parameter only if you need to trigger a function after it has finished executing.
Low Level AJAX
$.ajax (options) is the syntax for low level AJAX functions.
$.ajax provides more functionality than higher-level functions, but it is also more difficult to use.
The option parameter sets a Name|value pair that defines URL data, passwords, data types, filters, character sets, timeouts, and error functions.
JQuery AJAX Request



Request Description



$ (selector). Load (url,data,callback) loads the remote data into the selected element
$.ajax (options) loads the remote data into the XMLHttpRequest object
$.get (Url,data,callback,type) uses HTTP get to load remote data
$.post (Url,data,callback,type) uses HTTP post to load remote data
$.getjson (url,data,callback) uses HTTP get to load remote JSON data
$.getscript (Url,callback) loads and executes remote JavaScript files
(URL) The URL (address) of the data being loaded
(data) A key/value object sent to the server
(callback) The function that is executed when the data is loaded
(type) The types of data returned (Html,xml,json,jasonp,script,text)
(options) all key/value pairs for full AJAX requests



I'll take a look at the example when I talk so much.



$.ajax instance


The code is as follows

1.$.ajax asynchronous requests with JSON data
var aj = $.ajax ({
URL: ' productmanager_reverseupdate ',//Jump to action
data:{
Selrollback:selrollback,
Seloperatorscode:seloperatorscode,
Provincecode:provincecode,
Pass2:pass2
},
Type: ' Post ',
Cache:false,
DataType: ' JSON ',
Success:function (data) {
if (data.msg = = "true") {
View ("Modified successfully!") ");
Alert ("Modified successfully!") ");
Window.location.reload ();
}else{
View (DATA.MSG);
}
},
Error:function () {
View ("Exception!") ");
Alert ("Exception!") ");
}
});



2.$.ajax an asynchronous request that serializes the contents of a table as a string
function Notips () {
var Formparam = $ ("#form1"). Serialize ();//serialization table contents as strings
$.ajax ({
Type: ' Post ',
URL: ' Notice_notipsnotice ',
Data:formparam,
Cache:false,
DataType: ' JSON ',
Success:function (data) {
}
});
}



Asynchronous request for 3.$.ajax stitching URL
var Yz=$.ajax ({
Type: ' Post ',
URL: ' validatepwd2_checkpwd2?password2= ' +password2,
data:{},
Cache:false,
DataType: ' JSON ',
Success:function (data) {
if (data.msg = = "false")//the server returns FALSE, the value of VALIDATEPASSWORD2 is changed to Pwd2error, which is asynchronous and needs to consider the return time
{
Textpassword2.html ("<font color= ' red ' > Business password is incorrect!) </font> ");
$ ("#validatePassword2"). Val ("Pwd2error");
CheckPassword2 = false;
Return
}
},
Error:function () {}
});



4.$.ajax asynchronous request for splicing data
$.ajax ({
URL: ' <%=request.getcontextpath ()%>/kc/kc_checkmernameunique.action ',
Type: ' Post ',
Data: ' Mername= ' +values,
Async:false,//default to True asynchronous
Error:function () {
Alert (' Error ');
},
Success:function (data) {
$ ("#" +divs). HTML (data);
}
});






Jquery.get instance




Jquery.get (URL, [data], [Callback (data, Textstatus, XMLHttpRequest)], [datatype])



Returns:xmlhttprequest



URL string that contains the URL of the request being sent.



The data map or string is sent to the server with the request.



Callback (data, Textstatus, XMLHttpRequest) If the request is successfully executed.



Datatypethe type of data is expected from the server.



This is an abbreviated AJAX feature, which is equivalent to:


The code is as follows

$.ajax ({
Url:url,
Data:data,
Success:success,
Datatype:datatype
});



The tuning function successfully returns data passing, which will be an XML root element, a text string, a Web effects file, or a JSON object based on the MIME type of the response. It also passes the response text state.



In jquery 1.4, the successful callback function is also passed through the XMLHttpRequest object.



Most implementations will specify a successful handler:


The code is as follows

$.get (' ajax/test.html ', function (data) {
$ ('. Result '). HTML (data);
Alert (' Load was performed. ');
});



Jquery.post Instance



Jquery.post (URL, [data], [callback], [type]):
Use post to make asynchronous requests




Parameters:



URL (String): The URL address where the request is sent.



Data (MAP): (optional) The information to be sent to the server, expressed as a Key/value key-value pair.



Callback (function): (optional) the callback function (which is invoked only if the response return state is success) when loading succeeds.



Type (String): (optional) The official description is: type of data to is sent. The type that should actually be requested for the client (Json,xml, etc.)
1.html page (index.html)


The code is as follows


<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd
<meta http-equiv= "Content-type" Content= "text/html; charset=gb2312 "/>
<title>untitled document</title>
<script type=" Text/javascript "src= ' # ' "/jquery-1.3.2.js" ></script>
<script language= "javascript"
function Checkemail () {
 
  if ($ (' #email '). val () = "") {
    $ (' #msg '). HTML ("Please enter the email!");
    $ (' #email '). Focus;
    return false;
 }
  if ($ (' #address '). val () = "") {
    $ (' #msg '). HTML ("Please enter the address!");
    $ (' #address '). Focus;
    return false;
 }
  Ajax_post ();
}



Function Ajax_post () {
  $.post ("action.php", {email:$ (' #email '). Val (), address:$ (' #address '). Val ()},
  Function (data) {
   //$ (' #msg '). HTML ("Please enter the email!");
   //alert (data);
    $ (' #msg '). HTML (data);
 },
  "text";//the type returned here is: Json,html,xml,text
}
</script>


<body>
<form id= "Ajaxform" name= "Ajaxform" method= "post" action= "action.php" >
<p>
Email<input type= "text" name= "email" id= "email"/>

</p>
<p>
Address<input type= "text" name= "Address" id= "Address"/>
</p>
<p id= "MSG" ></p>
<p>
<input name= "Submit" type= "button" value= "Submit" onclick= "return Checkemail ()"/>
</p>
</form>
</body>


2.php page (action.php)


The code is as follows

<?php
$email = $_post["email"];
$address = $_post["Address"];

Echo $email;
Echo $address;
echo "Success";
?>



Jquery.getjson Instance



Jquery.getjson (URL, [data], [Callback (data, Textstatus)]
URL A string that contains the URL to which the request is sent.



Data map or string, sent to the server with the request



The callback (data, Textstatus) callback function is executed if the request succeeds.



Look at a simple example


The code is as follows

$.ajax ({
Url:url,
DataType: ' JSON ',
Data:data,
Success:callback
});



The callback is by returning the data, which will be a Web page effect object or array definition and parsing JSON structure using $. Parsejson () method.



Most implementations will specify a successful handler:


The code is as follows

$.getjson (' Ajax/test.json ', function (data) {
$ ('. Result '). html (' <p> ' + data.foo + ' </p> ')
+ ' <p> ' + data.baz[1] + ' </p> ');
});


This example, of course, relies on the JSON file structure:



{
"foo": "The quick brown fox jumps tutorial over the lazy dog."
"Bar": "ABCDEFG",
"Baz": [52, 97]
}


The code is as follows



<!doctype html>
<style>img{height:100px; float:left;} </style>
<script src= "Http://code.jquery.com/jquery-latest.min.js" ></script>
<body>
<div id= "Images" >



</div>
<script>$.getjson ("/?tags=cat&tagmode=any&format=json&jsoncallback=?"),
function (data) {
$.each (Data.items, function (I,item) {
$ ("if (i = = 3) return false;
});
});</script>



</body>


jquery $.getscript Instance




This function is shorthand for Ajax functions, equivalent to:


The code is as follows
$.ajax ({
Url:url,
DataType: "Script",
Success:success
});


The callback function here will pass in the returned JavaScript file. This is often not useful because the script is already running.



The loaded script executes in the global environment, so it can refer to other variables and use the JQuery function.



For example, load a test.js file that contains the following code:


The code is as follows
$ (". Result"). HTML ("<p>lorem ipsum dolor sit amet.</p>");


By referencing the file name, you can load and run the script:


  code is as follows

$.getscript ("Ajax/test.js", function () {
  alert ("Load was performed.");
});

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.