Explain the combined use of jquery and Ajax and Jsonp in JavaScript _jquery

Source: Internet
Author: User
Tags getscript

With XMLHttpRequest, browsers can interact with the server without refreshing the entire page, which is called Ajax (asynchronous JavaScript and XML). Ajax can provide users with a richer user experience.

Ajax requests are driven by JavaScript, sending a request to the URL via JavaScript code, and a callback function is triggered when the service side responds, where the callback function handles the information returned by the server. Because the entire process of sending requests and responses is asynchronous, the other Javascript code in the page continues to execute without interruption during this period.

JQuery certainly provides good support for Ajax, as well as an abstraction of the painful differences between browsers for AJAX support. It not only provides a full-featured $.ajax () method, but also a more convenient method such as $.get (), $.getscript (), $.getjson (), $.post (), and $ (). Load ().

Despite being named Ajax, many AJAX applications do not use XML, especially the JQuery Ajax application, most of them do not use XML, but more often than not: plain text, HTML, and JSON (JavaScript Object Notat ION).

In general, Ajax cannot execute requests across domains because of the same source policy (same protocol, same domain name, same port), except with scenarios such as JSONP (JSON with Padding) to achieve some restricted Cross-domain functionality.
Some important concepts about Ajax

Get vs POST, which is the two most common methods of sending requests to the server, and understanding the difference between the two methods is important for Ajax development.

A Get method is typically used to perform some non-destructive action (that is, only getting information from the server and not modifying the information on the server). For example, a search query service typically uses a GET request. In addition, a GET request may also be cached by the browser, which can cause unpredictable problems. In general, a GET request can only send data to the server by way of a query string.

The POST method is often used to perform destructive operations on the server (that is, to modify the data on the server). For example, when you publish a blog, you should use a POST request. Unlike get requests, there is no caching problem with POST requests. In a POST request, the query string can also submit data to the server as part of the URL, but this method is not recommended, and all data should be sent separately from the URL.

Data types, JQuery typically requires that the data type returned by the server is indicated, and that some cases where the write data type may already be contained in the method name, such as $.getjson (), and in addition, it is used as part of a configurable object that ultimately acts as a parameter to the $.ajax () method. Data types usually have the following:

    • Text: Plain text, used to transmit simple strings.
    • HTML: Used to transfer a section of HTML.
    • Script: Adding scripts to the page.
    • JSON: Transmits a formatted JSON object that can contain a string, array, or object.
    • JSONP: Used to transmit JSON data that is returned from another domain.
    • XML: Used to transmit custom XML format data.

Asynchronous execution, in Ajax, a refers to asynchronous (asynchronous). Speaking of which, it's possible that many jQuery beginners find it hard to understand what is called asynchronous, because Ajax requests are asynchronous by default, and the information returned by the server is not immediately available. The information returned by all service-side can only be handled in one callback function. For example, the following code is wrong:

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

The correct approach would be to process the data returned by the server in the callback function, which is executed when the Ajax request completes successfully, at which point the data from the server is obtained:

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

Homology policies and JSONP, as mentioned earlier, typically Ajax requests are limited to the same protocol (HTTP or HTTPS), the same port, the same domain name to execute correctly, but the HTML <script> tag does not have this limitation, it can load the script under any domain , that's what JQuery uses to get the ability to perform Ajax across domains.

The so-called JSONP, is the other domain's server to return to us is the JavaScript code, this code can be loaded into the HTML <script> tag, this JavaScript code contains a server from the other domain returns the JSON data, and to Provided in the form of a callback function. As a result, jQuery avoids the restriction of homology policy, and the curve has the ability to perform Ajax across domains.

Ajax Debugging tools, now newer browsers such as Chrome and Safari, and even IE have built-in debugging tools, Firefox also has a powerful FireBug plug-ins, with these debugging tools, can be very detailed view of the implementation of the AJAX process.
Some of the methods associated with Ajax

JQuery offers a number of simple Ajax methods, but their core is $.ajax, so the $.ajax must be understood correctly.

The $.ajax of JQuery is the most direct and efficient way to create AJAX requests, and its parameters are a JavaScript object that we can configure Ajax in very detail in this object. In addition, the $.ajax method can define the callback function for the success and failure of the AJAX request separately, and it features a configurable object as a parameter, allowing us to configure the object outside of 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 URL to request: ' post.php '/////

  () data to be sent to the server
  ///(will be converted to a query string, such as:? id=123)
  data: {id:123},
   
    //defines whether this Ajax request is a POST or a get
  type: "Get",//the

  data type returned by the server (S
  ) DataType: ' JSON ',////

  The callback function when Ajax successfully executes;
  //back The parameter of the tuning function is the data
  success:function (JSON) {
    $ (' 

Note:

About DataType: If the DataType defined here is not the same as the data format returned by the server, our code may fail and it is difficult to find out why, because the status code returned by HTTP does not show an error. So when executing an AJAX request, be sure to ensure that the data format returned by the server is consistent with the definition defined beforehand. In general, validating the Content-type in HTTP header information is an effective approach, and for JSON, the corresponding content-type should be application/json.

Some customization options for $.ajax

The $.ajax method has a lot of customization options, which is why this approach is powerful. To review all customization options, refer to the official documentation: http://api.jquery.com/jQuery.ajax/, which lists some of the most common options:

Async: The default value is True, and you can set it to False if you want Ajax to be performed in a synchronized fashion. Note that if you set this value to False, your other JavaScript code will be interrupted until the Ajax request is completed and the data returned by the server will be restored. Therefore, please use this option with caution.
Cache: Sets whether the data sent back by the server is cached. The default value is true for data in a format other than script and Jsonp. If set to False, when a request is sent to the server, a query string is added to the URL and the value of the string is the current timestamp to ensure that the URL for each request is different and of course there is no caching problem. The method for getting timestamps in JavaScript is new Date (). GetTime ().
Complete:ajax the callback function that fires when the request executes, regardless of whether the execution succeeds or fails, 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 execution (the callback function function (s) {alert (this)} is pointing to who?) )。 By default, this in the callback function points to the argument passed to the $.ajax method, which is the large object.
Data: The value to be sent to the server is either an object or a query string, such as Foo=bar&baz=bim.
DataType: The type of data returned by the server. If you do not set this option, JQuery will judge itself based on the MIME type of the server's return data.
Error: The callback function that will be triggered when the Ajax executes the error, which accepts the original request information and the status code.
JSONP: The callback function name that is required to execute the JSONP request, and the default value is "callback".
The callback function that will be triggered when the Success:ajax is executed successfully. In a function, you can get the information returned by the server (if DataType is set to JSON, the returned data should be a JavaScript object), and of course you can get the raw data information and status code returned by the server.
Timeout: Setting a timeout for Ajax requests is a time, in milliseconds.
Type: Specifies the method of the request, get or POST, the default value is get. Other methods, such as put and DELETE, are also available, but not all browsers support it.
URL: the URL to request.

Where the URL option is the only required option in all options, the other options are optional.
some simple methods

If you don't need so many configurable options and don't care about the Ajax execution errors, JQuery also provides some handy and easy ways to accomplish AJAX requests in a more concise way. In fact, these simple writing simply encapsulates the $.ajax and sets some options in advance.

JQuery provides an easy way to:

    • $.get: Performs a GET request on the given URL.
    • $.post: Performs a POST request on the given URL.
    • $.getscript: Adds a script to the page.
    • $.getjson: Executes a GET request, the information returned by the server should be JSON.

Each of these simple methods can pass the following parameters:

URL: The requested URL must be provided.
Data: Available to the server, optional. 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 a request has been successfully executed. Optional. The callback function accepts data returned by the server, and also includes the requested status code and original object.
Data type: The type of data returned by the service side. Optional.

    • Note: This option applies only to methods that do not specify a data type in their name.

The following are examples of three simple methods:

Gets either plain text or HTML
$.get ('/users.php ', {userid:1234}, function (resp) {
  console.log (resp);
});

Add a script to the page, and then execute the functions defined in the script.
$.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

The $.fn.load method is the only method that is invoked on the selector result set in all of the Ajax methods of JQuery. The $.fn.load method obtains information from the given URL and populates it with the elements contained in the selector result set. In addition, you can attach some selectors after the URL, and JQuery will eventually populate the corresponding HTML element with the matching selector.

Here is an example:

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

or
$ (' #newContent '). Load ('/foo.html #myDiv h1:first ', function (HTML) {
 alert (' Loaded! ');
});

Ajax and Forms

JQuery's Ajax is more of a divinity in dealing with forms. The two most useful methods are $.fn.serialize and $.fn.serializearray, and the following are their uses:

Converts the data in the form to the query string
$ (' #myForm '). Serialize ();

$ (' #myForm '). Serializearray ();
Converts the data in the form to an array of objects, such as:
[
  {name: ' Field1 ', value:123},
  {name: ' Field2 ', value: ' Hello World '}
]

Using JSONP

The nature of JSON is actually a cross-site scripting injection. There are a number of better sites that now offer JSONP services that allow us to get their data using their predefined APIs. Here is an example from the http://www.giantflyingsaucer.com/blog/?p=2682

Service-Side 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); c16/>}
});

jquery hides the implementation details of JSONP behind the scenes, and all we have to do is tell the jquery server that the name of the function is defined and that the data type we are requesting is JSONP, and that other aspects are no different from ordinary Ajax requests.
Ajax Events

Many times we need to do something at the beginning or end of an Ajax request, such as showing or hiding a loading ... Image. These jobs could have been implemented in each AJAX request, but JQuery provides a better way to bind Ajax events like normal events. To see the full list of events, you can access http://docs.jquery.com/Ajax_Events. Here 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.