Basic jquery tutorial (jquery fundamentals) -- (Part 7) Jquery Ajax

Source: Internet
Author: User
Tags getscript response code

 

Basic Jquery tutorial

Author: Rebecca Murphey

Original link address http://jqfundamentals.com/

With contributions by James Padolsey, Paul Irish, and others. See the GitHub repository for a complete history of contributions.

Copyright 2011

 

 

Jquery Ajax I. Overview

The XMLHttpRequest method allows the browser to communicate with the server without the need to reload the entire page. This method is the well-known Ajax (Asynchronous Javascript and XML), which provides a rich web page for user interaction experience.

Ajax requests are triggered by javascript code. When you call code to send a request to a URL address and receive a response, a callback function is triggered to process the request. Because the request is asynchronous, when the request is processed, your remaining code is still being executed. At this time, the callback function used to process the response is very important.

Jquery provides ajax support, which abstracts many methods to handle different browser problems. It also provides a method that includes all new features $. ajax and some easy-to-use methods, such as $. get (), $. getScript (), $. getJSON, $. post (), and $ (). load ().

Although the name Is ajax, most jquery applications do not use XML; on the contrary, they pass data through common HTML or JSON (JAvascript Object Notation.

Generally, ajax does not support cross-origin work. With the exception, JSONP (JSON with Padding) is supported, which allows restricted cross-origin features.

II. Key Concepts

To better use ajax-related methods in jquery, you must first understand some key concepts.

  • Get and Post

Get and Post are two common methods used to send requests to the server. It is important to understand the appropriate application scenarios of each method.

The Get method is generally used for Lossless operations-that is, you only obtain data from the server, rather than changing the data on the server. For example, a search service query is a Get request. Get requests can be cached by the browser, so if you don't know its features, there will be an unexpected thing. A Get request generally sends all data through a query string.

Post is generally used for Lossy operations-that is, you change the data operations on the server. For example, a Post request is used to save a blog. Post requests are generally not cached by browsers; query strings can be part of URLs, but data is generally sent as post data.

  • Data Type

Jquery generally requires some commands as the data type you obtain from an ajax request. In some cases, the method name specifies the data type. In other cases, it is specified by configuring part of the object. The following are some details:

Text

Used to transmit simple strings

Html

Used to transmit html statement blocks and place them on the page

Script

Add some new scripts to the page

Json

It is used to transmit json data. It can contain strings, arrays, and object types.

Note:

In jquery1.4, if the data in json format returned by your server is incorrect, the request will fail. You can access the http://json.org to understand the data in the correct json format, but in general, you should still generate json in a language-built approach on the server to avoid syntax errors.

Jsonp

It is used to transmit data from another application domain.

Xml

Transmit data in custom xml format

 

In most cases, I am a supporter of data transmission in json format because of its flexibility. Especially when html and data are transmitted simultaneously.

  • A Indicates asynchronous

Asynchronous in ajax is a concern for many new jquery users. Because ajax calls are asynchronous by default, the response does not take effect immediately. The response can only be processed using One callback function. For example, the following code does not work:

var response;$.get('foo.php', function(r) { response = r; });console.log(response); // undefined!

At the same time, we also need to pass a request to our callback function. This callback function will be executed after the request is successful, and then we can access the value returned by it.

$.get('foo.php', function(response) { console.log(response); });
  • Same Origin Policy and jsonp (Same-Origin Policy and JSONP)

Generally, ajax requests are limited to the same protocol (http or https), the same port, and the same domain as page requests. This restriction does not apply to scripts loaded using jquery's ajax method.

Another exception is requests for another domain in the jsonp service. In jsonp, the service provider allows you to respond to the requests you load to the page through the <script> script. This method avoids the same origin policy; the script will contain the data you requested and wrapped in the callback function you provided,

  • Ajax and Firebug

Firebug is very important for developing ajax requests. When an ajax request occurs, you can go to the Firebug Console

When you see them, you can click a request to expand it and take a look at its details, such as the request header, Response Header, response content, and more. If the ajax request does not achieve your expected results, you should first track the issue to find out where the error occurred.

Iii. ajax-related methods of jquery

Although jquery provides many convenient ajax-related methods, the core $. ajax method is the most important in general and it is necessary to master it. Let's first review this method and then briefly describe other methods.

I usually use the $. ajax method instead of the small ones. As you can see, it provides many features that are not available in small methods, and I think its syntax is easy to understand.

$. Ajax

Jquery's core $. ajax method is a powerful and direct method for creating ajax requests. It receives an object that contains all the instructions required by jquery to complete the request. $. Ajax is generally worthwhile because it will be confirmed if the callback is successful or fails. At the same time, it receives the features of configuration objects that can be separately defined, and also provides a good foundation for code reuse. To learn more about the configuration, visit the http://api.jquery.com/jQuery.ajax.

Example 7.1: Core $. ajax application

$.ajax({    // the URL for the request    url : 'post.php',    // the data to send    // (will be converted to a query string)    data : { id : 123 },    // whether this is a POST or GET request    type : 'GET',    // the type of data we expect back    dataType : 'json',    // code to run if the request succeeds;    // the response is passed to the function    success : function(json) {        $('

Note:

Record on data type settings: if the data format returned by the server is different from what you expected, your code will fail, and the cause is sometimes confusing, because the http response code does not report an error. When making ajax requests, make sure that your server returns the expected value and that the Content-type header is accurate to the data type. For example, for json data, the Content-type header is application/json.

$. Options of ajax

There are many options for the $. ajax method, which is its power. To obtain a complete list of optional items, visit http://api.jquery.com/jquery.ajax:

Async

If the request is sent synchronously, set it to false. The default value is true. Note: If you set this option to false, your request will block the execution of other code until the response is accepted.

Cache

Determine whether to use the cached response if permitted. By default, all other data types except "script" and "jsonp" are true. When it is set to false, the url will have a simple cache appended to it.

Complete

Whether the request succeeds or fails, the callback function starts to run when the request ends. This function receives unprocessed request objects and the text status of the request.

Context

In the domain where the callback function is run (that is, when this is used, the callback function is internally used ). By default, this inside the callback function points to the object originally passed to $. ajax.

Data

The data that will be passed to the server. It can be an object or a query string. For example, foo = bar & baz = bim

DataType

The data type you want to return from the server. By default, if dataType is not specified, jquery will refer to the response MIME type.

Error

If the request result is an error, the callback function is executed. This function receives unprocessed request objects and the text status of the request.

Jsonp

When you initiate a jsonp request, the callback function name is packaged into a query string for transmission. The default value is "callback ".

Success

If the request succeeds, the callback function is executed. This function receives response data (if the data type is json, It is forcibly converted into a javascript Object), and also accepts the text status of the request and the unprocessed request object.

Timeout

The millisecond representation of the waiting time before the request is considered failed.
Traditional

Set jquery1.4 to true to use parameter serialization. See: http://api.jquery.com/jQuery.param/ for details.

Type

Request type: "post" or "get ". The default value is "get ". Other request types, such as "put" and "delete. But not all browsers support them.

Url

Request url

The url option is the only required attribute in the $. ajax configuration object. Others are optional.

Convenient small Method

If you don't like the configurable $. ajax, you don't have to worry about it. jquery's ajax convenience method is also a powerful tool to implement ajax requests. These methods are implemented around the core $. ajax method, and the options of the $. ajax method are simply set.

As follows:

$. Get

Provide a Get request to the provided url

$. Post

Provide a POST request to the provided url

$. GetScript

Add a script to the page

$. GetJSON

Provide a GET request and expect to return a json data.

 

In each case, the method accepts the following parameters:

URL

URL of the request -- required

Data

Data passed to the server -- Optional. It can be an object or a query string. For example, foo = bar & baz = bim.

Note:

This option is not applicable to $. geScirpt.

Success callback

If the request succeeds, the callback function is optional. This function receives response data (if the data type is json, It is forcibly converted into a javascript Object), and also accepts the text status of the request and the unprocessed request object.

Datatype

Type of the data you want to return from the server -- Optional.

Note:

This option applies only to methods that cannot confirm the data type from the name.

Example 7.2: ajax with jquery in a small way

// get plain text or html$.get('/users.php', { userId : 1234 }, function(resp) {    console.log(resp);});// add a script to the page, then run a function defined in it$.getScript('/static/js/myScript.js', function() {    functionFromMyScript();});// get JSON-formatted data from the server$.getJSON('/details.php', function(resp) {    $.each(resp, function(k, v) {        console.log(k + ' : ' + v);    });});

 

$. Fn. load

$. Fn. load is unique in jquery's ajax method-it is called by a selected result. $. Fn. load method obtains html from a url and uses the obtained html to construct the selected element. In addition to providing a url for the method, you can also choose to provide a selector. jqueyr will search for matched content from the returned html.

Example 7.3: use $. fn. load to build elements

$('#newContent').load('/foo.html');

Example 7.4: use $. fn. load to construct selector-based elements

$('#newContent').load('/foo.html #myDiv h1:first', function(html) {  alert('Content updated!');});
Iv. ajax and forms

Jquery's ajax capabilities were well developed when dealing with forms. Jquery Form plug-in (jQuery Form plug-in) has good support for adding ajax capabilities to forms, so you should try to use this plug-in instead of repeating the wheel. But you should master the two simple jquery Methods: $. fn. serialize and $. fn. serializeArray.

Example 7.5: convert data into a query string

$('#myForm').serialize();

Example 7.6: Create an object array to contain form data

$('#myForm').serializeArray();// creates a structure like this:[    { name : 'field1', value : 123 },    { name : 'field2', value : 'hello world' }]
 
5. Use jsonp

The emergence of jsonp-essentially an exaggerated scripting hacker-provides powerful support for content transmission. Many well-known websites provide the jsonp service, allowing you to access their content through an api. Yahoo! Query is a popular jsonp data code. In the following example, we will use it to get news about cats.

7.7: Use YQL and JSONP

$.ajax({    url : 'http://query.yahooapis.com/v1/public/yql',    // the name of the callback parameter,    // as specified by the YQL service    jsonp : 'callback',    // tell jQuery we're expecting JSONP    dataType : 'jsonp',    // tell YQL what we want and that we want JSON    data : {        q : 'select title,abstract,url from search.news where query="cat"',        format : 'json'    },    // work with the response    success : function(response) {        console.log(response);    }});

Jquery's behind-the-scenes processing is all the complex operations of jsonp-what we need to do is to tell jquery The Name Of The jsonp callback function that is determined by YQL, therefore, the entire process is like a normal ajax request.

6. ajax events

Whether an ajax request starts or ends, we often want to perform a specific operation, such as displaying or hiding a logon indicator. At this time, you can bind an ajax event to an element, just like binding other events, rather than defining an action internally for each ajax request. To learn more about ajax events, visit: http://docs.jquery.com/Ajax_Events.

Example 7.8: use an ajax event to start a logon indicator.

$('#loading_indicator')    .ajaxStart(function() { $(this).show(); })    .ajaxStop(function() { $(this).hide(); });
VII. Exercises

(Omitted)

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.