Jquery ajax getting started instance ($. ajax $. get $. post $. getJSON $. getScript

Source: Internet
Author: User
Tags getscript

In jquery, ajax can be classified as $. ajax $. get $. post $. getJSON $. there are several types of getscripts. I have found some examples to share with you. It is estimated that jquery ajax is really simple after reading them.


What Is AJAX?

AJAX = Asynchronous JavaScript and XML.

AJAX is a technology for creating fast dynamic web pages.
AJAX allows asynchronous updates on webpages by exchanging a small amount of data with the server in the background. This means that it is possible to update part of the webpage without reloading the whole page.

AJAX and jQuery
JQuery provides a rich library of functions (methods) for AJAX development.
Using jQuery AJAX and HTTP Get and HTTP Post, you can request TXT, HTML, XML, or JSON from a remote server.
In addition, you can directly load remote data into the selected HTML element of the webpage!
Write less and do more
JQuery's load function is a simple (but powerful) AJAX function. Its syntax is as follows:

$ (Selector). load (url, data, callback)

Use selector to define the HTML element to be changed and use url parameters to specify the web address of the data.
Try it yourself
The data parameter is required only when you want to send data to the server. You must use the callback parameter only when you need to trigger a function after execution.
Low Level AJAX
$. Ajax (options) is the syntax of low-level AJAX functions.
$. Ajax provides more functions than high-level functions, but it is also more difficult to use.
The option parameter is set to the name | value pair, which defines url data, password, data type, filter, Character Set, timeout, and error functions.
JQuery AJAX request

Request description

$ (Selector). load (url, data, callback) load remote data to the selected Element
$. Ajax (options) Load remote data to the XMLHttpRequest object
$. Get (url, data, callback, type) use 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 of the loaded data (address)
Key/value object of data sent to the server
(Callback) functions executed when data is loaded
(Type) type of the returned data (html, xml, json, jasonp, script, text)
(Options) all key/value pair options of the complete AJAX request

After talking so much, let's take a look at the instance.

$. Ajax instance

The Code is as follows: Copy code

// 1. $. ajax asynchronous request 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 serialize asynchronous requests whose table content is a string
Function noTips (){
Var formParam = $ ("# form1"). serialize (); // serialize the table content as a string
$. Ajax ({
Type: 'post ',
Url: 'notice _ noTipsNotice ',
Data: formParam,
Cache: false,
DataType: 'json ',
Success: function (data ){
}
});
}


// 3. $. asynchronous request for url Splicing
Var yz = $. ajax ({
Type: 'post ',
Url: 'validatepwd2 _ checkPwd2? Password2 = '+ password2,
Data :{},
Cache: false,
DataType: 'json ',
Success: function (data ){
If (data. msg = "false") // if the server returns false, change the value of validatePassword2 to pwd2Error. This is asynchronous and the return time must be considered.
{
TextPassword2.html ("<font color = 'red'> incorrect business password! </Font> ");
$ ("# ValidatePassword2"). val ("pwd2Error ");
CheckPassword2 = false;
Return;
}
},
Error: function (){}
});


// 4. $. ajax Concatenates the asynchronous request of data
$. Ajax ({
Url: '<% = request. getContextPath () %>/kc/kc_checkMerNameUnique.action ',
Type: 'post ',
Data: 'mername = '+ values,
Async: false, // The default value is true asynchronous.
Error: function (){
Alert ('error ');
},
Success: function (data ){
$ ("#" Nvidivs#.html (data );
}
});


 

Jquery. get instance


Jquery. get (url, [data], [callback (data, textstatus, xmlhttprequest)], [datatype])

Returns: xmlhttprequest

Url string. The request containing the url is sent.

Data Map or string sent to the server with the request.

Callback (data, textstatus, xmlhttprequest), if the request is successfully executed.

Data of the datatypethe type is expected from the server.

This is an abbreviated ajax function, which is equivalent:

The Code is as follows: Copy code

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


 

The data returned by the call function is passed, which is an xml root element, text string, webpage special effect file, or a json object based on the response's mime type. It also passes the response text status.

In jquery 1.4, the successful callback function also uses the xmlhttprequest object.

Most implementations will specify a successful handler:

The Code is as follows: Copy code

$. Get ('ajax/test.html ', function (data ){
Certificate ('.result').html (data );
Alert ('Load was saved med .');
});


JQuery. post instance

JQuery. post (url, [data], [callback], [type]):
Use POST for asynchronous requests


Parameters:

Url (String): the URL of the request.

Data (Map): (optional) data to be sent to the server, expressed in Key/value pairs.

Callback (Function): (optional) callback Function when the load is successful (this method is called only when the Response returns success ).

Type (String): (optional) the official description is: Type of data to be sent. In fact, it should be the client request type (JSON, XML, and so on)
1.html page (index.html)

The Code is as follows: Copy code

<! 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>
<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 () = ""){
Certificate ('{msg'}.html ("please enter the email! ");
$ ('# Email'). focus;
Return false;
}
If ($ ('# address'). val () = ""){
Certificate ('{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 ){
// Certificate ('{msg'}.html ("please enter the email! ");
// Alert (data );
Certificate ('{msg'}.html (data );
},
"Text"); // The returned types include json, html, xml, and text.
}
</Script>
</Head>

<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>
</Html>

2. php page (action. php)

The Code is as follows: Copy code

<? 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 containing the url. 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 is successful.

Look at a simple instance

The Code is as follows: Copy code

$. Ajax ({
Url: url,
Datatype: 'json ',
Data: data,
Success: callback
});


The callback uses the returned data, which is a webpage special effect object or an array to define and parse the json structure using $. Parsejson () method.

Most implementations will specify a successful handler:

The Code is as follows: Copy code

$. Getjson ('ajax/test. json', function (data ){
Certificate ('.result'{.html ('<p>' + data. foo + '</p>'
+ '<P>' + data. baz [1] + '</p> ');
});

This example, of course, depends 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: Copy code


<! Doctype html>
<Html>
<Head>
<Style> img {height: 100px; float: left ;}</style>
<Script src = "http://code.jquery.com/jquery-latest.min.js"> </script>
</Head>
<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>
</Html>

Jquery $. getScript instance


This function is short for Ajax functions and is equivalent:

The Code is as follows: Copy code
$. Ajax ({
Url: url,
DataType: "script ",
Success: success
});

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

The loaded script is executed in the global environment. Therefore, other variables can be referenced and jQuery functions can be used.

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

The Code is as follows: Copy code
$ (". Result" pai.html ("<p> Lorem ipsum dolor sit amet. </p> ");

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

The Code is as follows: Copy code

$. GetScript ("ajax/test. js", function (){
Alert ("Load was saved med .");
});

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.