Details about the combined use of jQuery, Ajax, and JSONP in JavaScript

Source: Internet
Author: User
Tags getscript
This article mainly introduces the combined use of jQuery, Ajax and JSONP in JavaScript. the asynchronous structure of jQuery library and Ajax and JSON data transmission are also the most commonly used in JS routine programming, for more information, see XMLHttpRequest. the browser can interact with the server without refreshing the entire page. This is called Ajax (Asynchronous JavaScript and XML ). Ajax can provide users with a richer user experience.


Ajax requests are driven by JavaScript and send a request to the URL through JavaScript code. When the server responds, a callback function is triggered. Here, the callback function processes the information returned by the server. Because the whole process of sending requests and responses is asynchronous, other Javascript code on the page continues to be executed during this period without interruption.

JQuery also provides excellent support for Ajax, and abstracts the painful differences of various browsers in Ajax support. It not only provides a full-featured $. ajax () methods, such as $. get (), $. getScript (), $. getJSON (), $. post () and $ (). load () and other easier methods.

Although named Ajax, XML is not used in many Ajax applications, especially Ajax applications in jQuery, but XML is not used in most cases: plain text, HTML, and JSON (JavaScript Object Notation ).

Generally, Ajax cannot execute requests across regions due to the Same Origin Policy (same protocol, same domain name, and same port), unless it uses a scheme such as JSONP (JSON with Padding, to implement some limited cross-origin functions.
Some important concepts about Ajax

GET vs POST: This is the two most commonly used methods for sending requests to the server. correct understanding of the differences between the two methods is very important for Ajax development.

The GET method is usually used to perform some non-destructive operations (that is, to obtain information only from the server without modifying the information on the server ). For example, the search and query service generally uses GET requests. In addition, GET requests may be cached by the browser, which may cause some unpredictable problems. Generally, GET requests can only send data to the server by querying strings.

The POST method is usually used to perform some destructive operations on the server (that is, the data on the server will be modified ). For example, when you POST a blog, the POST request is used. Unlike GET requests, POST requests do not have cache problems. In a POST request, the query string can also submit data to the server as part of the URL. However, this method is not recommended. All data should be sent separately from the URL.

Data Type. jQuery usually specifies the data type returned by the server. In some cases, the data type may already be included in the method name, for example, $. getJSON (), in addition, it will be used as a part of a configurable object, and the object will eventually act as $. parameters of the ajax () method. There are usually the following types of data:

  • Text: plain text, used to transmit simple strings.
  • Html: used to transmit a piece of HTML.
  • Script: Add a script to the page.
  • Json: Transfers formatted JSON objects, which can contain strings, arrays, or objects.
  • Jsonp: used to transmit JSON data returned from other domains.
  • Xml: used to transmit custom XML format data.

Asynchronous execution. In Ajax, A refers to Asynchronous ). Speaking of this, it may be difficult for many jQuery beginners to understand what is asynchronous at once, because Ajax requests are asynchronous by default, and the information returned by the server cannot be obtained immediately. All information returned by the server can only be processed in one callback function. The following code is incorrect:


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


The correct method should be to process the data returned by the server in the callback function. The callback function is executed only when the Ajax request is successfully completed. In this case, the data from the server can be obtained:


$.get('foo.php', function(response) { console.log(response); });


Same-origin policy and JSONP, as mentioned earlier, Ajax requests can be correctly executed only under the same protocol (http or https), the same port, and the same domain name, however, the HTML script tag does not have this restriction. It can load scripts in any domain. jQuery can use this to execute Ajax across domains.

The so-called JSONP is the JavaScript code that the server of other domains returns to us. This code can be loaded into the script tag in HTML, this JavaScript code contains JSON data returned from the server in other domains and is provided as a callback function. In this way, jQuery avoids the restriction of the same-origin policy, and the curve has the ability to execute Ajax across domains.

Ajax debugging tools, new browsers such as Chrome and Safari, and even IE have built-in debugging tools. Firefox also has powerful FireBug plug-ins. With these debugging tools, you can view the Ajax execution process in detail.
Ajax-related methods

JQuery provides a variety of simple Ajax methods, but their core is $. ajax, so you must understand $. ajax correctly.

$. Ajax of jQuery is the most direct and effective method for creating Ajax requests. Its parameter is a JavaScript Object. We can configure Ajax in detail in this object. In addition, $. the ajax method can also define the callback functions when the Ajax request succeeds or fails. It uses a configurable object as the parameter feature, so that we can configure this object outside the Ajax method, and then pass it in, which is very helpful for code reuse. Detailed documentation on this method: http://api.jquery.com/jQuery.ajax/

A typical example is as follows:


$ .ajax ({
   // URL to request
   url: 'post.php',

   // data to be sent to the server
   // (will be converted into a query string, such as:? Id = 123)
   data: {id: 123},

   // Define if this Ajax request is POST or GET
   type: 'GET',

   // Data type returned by the server
   dataType: 'json',

   // callback function when Ajax is successfully executed;
   // The parameter of the callback function is the data returned by the server
   success: function (json) {
     $ (''). text (json.title) .appendTo ('body');
     $ ('
')
       .html (json.html) .appendTo ('body');
   },

   // if Ajax execution fails;
   // will return the original error message and status code
   // passed into this callback function
   error: function (xhr, status) {
     alert ('Sorry, there was a problem!');
   },

   // Here is the callback function that will be triggered regardless of the successful execution of Ajax
   complete: function (xhr, status) {
     alert ('The request is complete!');
   }
});



Note:

DataType: If the dataType defined here is different from the data format returned by the server, our code may fail to be executed, and it is difficult to identify the cause, because the HTTP return Status Code does not show an error. Therefore, when executing an Ajax request, make sure that the data format returned by the server is consistent with that defined in advance. Generally, it is effective to verify the Content-type in the HTTP header. For JSON, the corresponding Content-type should be application/json.

$. Some custom ajax options

$. The ajax method has many custom options, which is also the reason for its powerful functionality. To view all custom options, refer to the official documentation: http://api.jquery.com/jquery.ajax/. the following lists only a few commonly used items:

Async: The default value is true. If Ajax is required for synchronization, set it to false. Please note that if this value is set to false, your other JavaScript code will be interrupted until the Ajax request is complete and the data returned by the server will be restored. Therefore, use this option with caution.
Cache: determines whether to cache data sent back by the server. The default value is true for data in other formats than "script" and "jsonp. If it is set to false, a query string is added to the URL when a request is sent to the server. The string value is the current timestamp, to ensure that the URLs of each request are different, of course there is no cache problem. The method for obtaining the timestamp in JavaScript is new Date (). getTime ().
Complete: the callback function triggered when the Ajax request is executed. Whether the execution is successful or not, the callback function is triggered. The callback function can accept the original information and status code returned by the server.
Context: defines the scope of the callback function during execution (which of the callback function (s) {alert (this)} points ?). By default, this in the callback function points to the parameter passed to the $. ajax method, that is, the large object.
Data: The data to be sent to the server. The value can be an object or a query string, for example, foo = bar & baz = bim.
DataType: type of data returned by the server. If this option is not set, jQuery determines the MIME type of the data returned by the server.
Error: the callback function that is triggered when an Ajax execution error occurs. This function accepts the original request information and status code.
Jsonp: Specifies the name of the callback function to be used to execute a JSONP request. The default value is "callback ".
Success: the callback function that will be triggered when Ajax is successfully executed. In the function, you can obtain the information returned by the server (if dataType is set to JSON, the returned data should be a JavaScript Object). Of course, you can also obtain the original data and status code returned by the server.
Timeout: Set a timeout value for an Ajax request in milliseconds.
Type: Specify the request method, GET or POST. The default value is GET. Other methods such as PUT and DELETE can also be used, but not all browsers support them.
Url: the URL to be requested.

The url option is the only required option among all options. Other options are optional.
Some simple methods

If you don't need so many configurable options or handle Ajax execution errors, jQuery also provides some very useful and easy methods to complete Ajax requests in a more concise way. In fact, these simple statements only encapsulate $. ajax and set some options in advance.

JQuery provides the following simple methods:

  • $. Get: Execute the GET request on the given URL.
  • $. Post: executes the POST request on the given URL.
  • $. GetScript: Add a script to the page.
  • $. GetJSON: executes a GET request, and the information returned by the server is JSON.

The following parameters can be passed in each of the preceding methods:

Url: the requested URL, which must be provided.
Data: the data sent to the server. Optional. It can be an object or a query string, such as foo = bar & baz = bim.

  • Note: This option does not apply to $. getScript.

A callback function: This callback function is triggered after the request is successfully executed. Optional. The callback function accepts the data returned by the server, including the Request status code and the original object.
Data type: the type of data returned by the server. Optional.

  • Note: This option applies only to methods with no data type specified in their names.

The following is an example of three simple methods:


// Get plain text or html
$ .get ('/ users.php', {userId: 1234}, function (resp) {
   console.log (resp);
});

// Add a script to the page and execute the function defined in the script.
$ .getScript ('/ static / js / myScript.js', function () {
   functionFromMyScript ();
});

// Get data in JSON format from the server.
$ .getJSON ('/ details.php', function (resp) {
   $ .each (resp, function (k, v) {
     console.log (k + ':' + v);
   });
});


$. Fn. load

$. Fn. load is the only method called in all Ajax methods of jQuery In the selector result set. The $. fn. load method obtains information from the given URL and then fills in the elements contained in the selector result set. In addition, some selectors can be appended to the URL. jQuery will only fill in the content matching the selector to the corresponding HTML element.

The following is an example:


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

// or
$ ('# newContent'). load ('/ foo.html #myDiv h1: first', function (html) {
  alert ('Loading complete!');
});


Ajax and forms

JQuery's Ajax is even more powerful in dealing with forms. The two most useful methods are $. fn. serialize and $. fn. serializeArray. Their usage is as follows:


// Turn the data in the form into a query string
$ ('# myForm'). serialize ();

$ ('# myForm'). serializeArray ();
// Convert the data in the form into an array of objects, such as:
[
   {name: 'field1', value: 123},
   {name: 'field2', value: 'hello world'}
]


Use JSONP

The essence of JSON is actually a Cross-Site Script Injection. Many good websites now provide the JSONP service, allowing us to use their predefined APIs to obtain their data. Below is an example from http://www.giantflyingsaucer.com/blog? P = 2682

Server code:


<?php
  header("content-type: text/javascript");

  if(isset($_GET['name']) && isset($_GET['callback'])) {
    $obj->name = $_GET['name'];
    $obj->message = "Hello " . $obj->name;

    echo $_GET['callback']. '(' . json_encode($obj) . ');';
  }
?>


Client code:


$.ajax({
  url: 'http://otherDomail.com:8080/JSONP/jsonp-demo.php',
  data: {name: 'Super man'},
  dataType: 'jsonp',
  jsonp: 'callback',
  success: function( response ) {
    console.log( response.message );
  }
});


JQuery hides the Implementation Details of JSONP behind the scenes. What we need to do is to tell the jQuery server the defined function name and the requested data type is JSONP, other aspects are no different from common Ajax requests.
Ajax events

In many cases, we need to perform some operations at the beginning or end of an Ajax request, such as displaying or hiding a loading... Image. These jobs can be implemented in each Ajax request, but jQuery provides a better way to bind Ajax events just like a common event. To view the list of all events, visit http://docs.jquery.com/ajax_events. The following is a simple example:


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

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.