Home > Article > Web Front-end > Detailed explanation of the joint use of jQuery, Ajax and JSONP in JavaScript_jquery
With the help of XMLHttpRequest, the browser can interact with the server without refreshing the entire page. This is the so-called Ajax (Asynchronous JavaScript and XML). Ajax can provide users with a richer user experience.
Ajax requests are driven by JavaScript. A request is sent to the URL through JavaScript code. When the server responds, a callback function will be triggered. The information returned by the server can be processed in the callback function. Since the entire process of sending requests and responses is asynchronous, other Javascript codes in the page will continue to execute during this period without interruption.
jQuery certainly provides good support for Ajax, and it also abstracts away the painful differences in Ajax support among various browsers. It not only provides the full-featured $.ajax() method, but also more functions such as $.get(), $.getScript(), $.getJSON(), $.post() and $().load(), etc. For a simple method.
Although it is named Ajax, many Ajax applications do not use XML, especially jQuery Ajax applications. Most of them do not use XML; instead, they are more commonly used: plain text, HTML and JSON (JavaScript) Object Notation).
Generally, due to the restrictions of the same-origin policy (same protocol, same domain name, same port), Ajax cannot perform cross-domain requests, unless a solution such as JSONP (JSON with Padding) is used to achieve some affected requests. Limited cross-domain functionality.
Some important concepts about Ajax
GET vs POST, these are the two most commonly used methods of sending requests to the server. A correct understanding of the differences between these two methods is very important for Ajax development.
The GET method is usually used to perform some non-destructive operations (that is, only obtain information from the server without modifying the information on the server). For example, search query services typically use GET requests. In addition, GET requests may also be cached by the browser, which may cause some unpredictable problems. Generally, GET requests can only send data to the server through query strings.
The POST method is usually used to perform some destructive operations on the server (that is, modify the data on the server). For example, when you publish a blog post, you should use a POST request. Unlike GET requests, POST requests do not have caching issues. In POST requests, the query string as part of the URL can also submit data to the server, but this method is not recommended. All data should be sent separately from the URL.
Data type, jQuery usually requires specifying the data type returned by the server. In some cases, the data type may already be included in the method name, such as $.getJSON(). Otherwise, it will be used as an available Part of the configured object that will eventually be used as a parameter of the $.ajax() method. Data types usually include the following:
Asynchronous execution, the A in Ajax refers to asynchronous. At this point, it may be difficult for many jQuery beginners to understand what asynchronous is, because Ajax requests are asynchronous by default, and the information returned by the server is not immediately available. All information returned by the server can only be processed in a 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 should be to process the data returned by the server in the callback function. The callback function is only executed when the Ajax request is successfully completed. Only at this time can the data from the server be obtained:
$.get('foo.php', function(response) { console.log(response); });
同源策略及 JSONP,前面已经说过,一般情况下 Ajax 的请求会被限制在相同协议(http 或 https)、相同端口、相同域名下才能正确执行,但是 HTML 的 3f1c4e4b6b16bbbd69b2ee476dc4f83a 标签却无此限制,它可以载入任何域下的脚本,jQuery 正是利用了这一点才得以拥有跨域执行 Ajax 的能力。
所谓 JSONP,就是其它域的服务端返回给我们的是 JavaScript 代码,这段代码可以被加载到 HTML 中的 3f1c4e4b6b16bbbd69b2ee476dc4f83a 标签中,这段 JavaScript 代码中包含有从其它域下的服务端返回的 JSON 数据,并以回调函数的形式提供。这样一来 jQuery 就回避了同源策略的限制,曲线拥有了跨域执行 Ajax 的能力。
Ajax 调试工具,现在比较新的浏览器如 Chrome 和 Safari,甚至 IE 都内置了调试工具,Firefox 也有无比强大 FireBug 插件,借助于这些调试工具,可以非常详细的查看 Ajax 的执行过程。
和 Ajax 相关的一些方法
jQuery 提供了好多种简便的 Ajax 方法,但是它们的核心都是 $.ajax,所以必须正确理解 $.ajax。
jQuery 的 $.ajax 是创建 Ajax 请求中最直接也是最有效的方法,它的参数是一个 JavaScript 对象,我们可以在这个对象中对 Ajax 作非常详细的配置。另外,$.ajax 方法还可以分别定义 Ajax 请求成功和失败时的回调函数;而且它以一个可配置的对象作为参数的特性,使得我们可以在 Ajax 方法外配置这个对象,然后再传进来,这非常有助于实现代码复用。关于这个方法的详细文档:http://api.jquery.com/jQuery.ajax/
一个典型的示例如下:
$.ajax({ // 要请求的 URL url : 'post.php', // 要发给服务端的数据 // (将会转化为查询字符串,如:?id=123) data : { id : 123 }, // 定义此 Ajax 请求是 POST 还是 GET type : 'GET', // 服务端返回的数据类型 dataType : 'json', // Ajax 成功执行时的回调函数; // 回调函数的参数即为服务端返回的数据 success : function(json) { $('<h1/>').text(json.title).appendTo('body'); $('<div class="content"/>') .html(json.html).appendTo('body'); }, // 如果 Ajax 执行失败; // 将返回原始错误信息以及状态码 // 传入这个回调函数中 error : function(xhr, status) { alert('Sorry, there was a problem!'); }, // 这里是无论 Ajax 是否成功执行都会触发的回调函数 complete : function(xhr, status) { alert('The request is complete!'); } });
Remarks:
About dataType: If the dataType defined here is different from the data format returned by the server, our code may fail to execute, and it is difficult to find out the reason because the status code returned by HTTP does not show an error. Therefore, when executing an Ajax request, you must ensure that the data format returned by the server is consistent with the predefined definition. Usually, it is effective to verify the Content-type in the HTTP header information. For JSON, the corresponding Content-type should be application/json.
Some customization options for $.ajax
The $.ajax method has many customization options, which is why this method is so powerful. To check out all the customization options, you can refer to the official documentation: http://api.jquery.com/jQuery.ajax/. Only some commonly used options are listed below:
async: The default value is true. If you need Ajax to be executed synchronously, you can set it to false. Please 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 is received. So, please use this option with caution.
cache: Set whether to cache the data sent back by the server. The default value is true for data in formats other than "script" and "jsonp". If it is set to false, when sending a request to the server, a query string will be added to the URL. The value of the string is the current timestamp to ensure that the URL for each request is different, and of course it does not exist. There's a caching problem. The method to get timestamp in JavaScript is new Date().getTime().
Complete: The callback function triggered when the Ajax request is completed. This callback function will be triggered regardless of whether the execution is successful or not. This callback function can accept the original information and status code returned by the server.
Context: Define the scope when the callback function is executed (who does this in the callback function function(s) {alert(this)} point to?). By default, this in the callback function points to the parameter passed to the $.ajax method, which is the large object.
Data: The data to be sent to the server. Its value can be 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 determine it based on the MIME type of the data returned by the server.
Error: The callback function that will be triggered when an Ajax execution error occurs. This function accepts the original request information and status code.
jsonp: The name of the callback function that needs to be specified when executing 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 get 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 get the original data information and status code returned by the server.
Timeout: Set a timeout for Ajax requests, 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, and the other options are optional.
Some simple methods
If you don’t need so many configurable options and don’t care about handling Ajax execution errors, jQuery also provides some very useful and convenient methods to complete Ajax requests in a more concise way. In fact, these simple writing methods just encapsulate $.ajax and preset certain options.
The simple method provided by jQuery is as follows:
The following parameters can be passed in each of the above simple methods:
url: The requested URL, must be provided.
Data: Data sent to the server, optional. Can be an object or a query string, such as foo=bar&baz=bim.
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 status code of the request and the original object.
Data type: The type of data returned by the server. Optional.
下面是三个简便方法的示例:
// 获取纯文本或者 html $.get('/users.php', { userId : 1234 }, function(resp) { console.log(resp); }); // 向页面中添加脚本,然后执行脚本中定义的函数。 $.getScript('/static/js/myScript.js', function() { functionFromMyScript(); }); // 从服务端获取 JSON 格式的数据。 $.getJSON('/details.php', function(resp) { $.each(resp, function(k, v) { console.log(k + ' : ' + v); }); });
$.fn.load
$.fn.load 方法是 jQuery 所有 Ajax 方法中唯一在选择器结果集上调用的方法。$.fn.load 方法从给定的 URL 上获取信息,然后填充到选择器结果集包含的元素中。另外,在 URL 后面还可以附加一些选择器,jQuery 最终只会把跟选择器相匹配的内容填充到对应的 HTML 元素中。
下面是示例:
$('#newContent').load('/foo.html'); // 或 $('#newContent').load('/foo.html #myDiv h1:first', function(html) { alert('加载完毕!'); });
Ajax 和 表单
在跟表单打交道方面,jQuery 的 Ajax 更显神威。最为有用的两个方法就是 $.fn.serialize 和 $.fn.serializeArray,下面是它们的用法:
// 将表单中数据转化为查询字符串 $('#myForm').serialize(); $('#myForm').serializeArray(); // 将表单中数据转化为对象数组,如: [ { name : 'field1', value : 123 }, { name : 'field2', value : 'hello world' } ]
使用 JSONP
JSON 的本质其实是一种跨站点脚本注入。现在有很多比较好的网站都提供了 JSONP 服务,允许我们用他们预先定义好的 API 获取他们的数据。下面是一个示例,来源于 http://www.giantflyingsaucer.com/blog/?p=2682
服务端代码:
<?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) . ');'; } ?>
客户端代码:
$.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 把 JSONP 的实现细节隐藏在幕后,我们要做的就是告诉 jQuery 服务端定义好的函数名以及我们请求的数据类型是 JSONP,其它方面和普通的 Ajax 请求没什么区别。
Ajax 事件
很多时候我们都需要在 Ajax 请求开始或结束时做一些操作,例如显示或隐藏一个 loading… 图片。这些工作本可以在每个 Ajax 请求中各自实现,但是 jQuery 提供了更好的方法,你可以像绑定普通事件一样绑定 Ajax 事件。若要参阅全部事件列表,可访问 http://docs.jquery.com/Ajax_Events。下面是简单示例:
$('#loading_indicator') .ajaxStart(function() { $(this).show(); }) .ajaxStop(function() { $(this).hide(); });