Summary of key points
Entering 2013…the way we use the jQuery.Ajax() function has changed in recent versions. With this in mind, and the older examples slightly outdated, I wrote 5 new jQuery.ajax() examples (jQuery 1.9) to show how to use Ajax with newer versions of jQuery 1.9.x and 2.0. New methods have some advantages over old methods.
I will try to keep this post updated with Ajax code snippets for reference. As always, comments are welcome.
Some quick reminders for learners: - The .done() method replaces the deprecated jqXHR.success() method. - The .fail() method replaces the deprecated .error() method. - The .always() method replaces the deprecated .complete() method.
jQuery 1.9 Ajax Example 1 – Subscribe to Newsletter
This example shows the basic Ajax request to subscribe to a newsletter for sending names and emails to backend scripts.
var subscribeRequest = $.ajax({ type: "POST", url: "subscribe.php", data: { subscriberName: $('#name').val(), emailAddress: $('#email').val() } }); subscribeRequest.done(function(msg) { alert( "您已成功订阅我们的邮件列表。" ); }); subscribeRequest.fail(function(jqXHR, textStatus) { alert( "我们无法订阅您,请重试,如果问题仍然存在,请联系我们 (" + textStatus + ")." ); });
jQuery 1.9 Ajax Example 2 – Request Timeout
This example shows how to catch errors and failures, such as timeouts for Ajax requests. > Set a timeout time in milliseconds for the request. The timeout starts when the $.ajax call is issued; if multiple other requests are in progress and there is no available connection to the browser, the request may time out before sending. In Firefox 3.0 alone, scripts and JSONP requests cannot be canceled by timeout; it will run even if the script arrives after the timeout.
var newDataRequest = $.ajax({ url: "getNewData.php", timeout: 30000, // 30 秒后超时 data: { timestamp: new Date().getTime() } }); newDataRequest.done(function(data) { console.log(data); }); newDataRequest.fail(function(jqXHR, textStatus) { if (jqXHR.status === 0) { alert('未连接。请验证网络。'); } else if (jqXHR.status == 404) { alert('请求的页面未找到。[404]'); } else if (jqXHR.status == 500) { alert('内部服务器错误 [500]。'); } else if (exception === 'parsererror') { alert('请求的 JSON 解析失败。'); } else if (exception === 'timeout') { alert('超时错误。'); } else if (exception === 'abort') { alert('Ajax 请求已中止。'); } else { alert('未捕获的错误。\n' + jqXHR.responseText); } });
jQuery 1.9 Ajax Example 3 – Datafilter
This example shows how to use the dataFilter function to process the raw data returned by an Ajax request.
var filterDataRequest = $.ajax({ url: "getData.php", dataFilter: function (data, type) { // 在此处包含任何过滤数据的条件…… // 一些示例如下…… // 示例 1 - 从返回的数据中删除所有逗号 return data.replace(",", ""); // 示例 2 - 如果数据是 json,则以某种方式处理它 if (type === 'json') { var parsed_data = JSON.parse(data); $.each(parsed_data, function(i, item) { // 处理 json 数据 }); return JSON.stringify(parsed_data); } } }); filterDataRequest.done(function(data) { console.log(data); }); filterDataRequest.fail(function(jqXHR, textStatus) { console.log( "Ajax 请求失败... (" + textStatus + ' - ' + jqXHR.responseText + ")." ); });
jQuery 1.9 Ajax Example 4 – MIME Type
This example shows how to specify the available content response header type on XMLHttpRequest. If you explicitly pass content-type to $.ajax(), it will always be sent to the server (even if no data is sent). If the character set is not specified, the data will be transferred to the server using the server's default character set; this data must be properly decoded on the server side.
var subscribeRequest = $.ajax({ type: "POST", url: "subscribe.php", data: { subscriberName: $('#name').val(), emailAddress: $('#email').val() } }); subscribeRequest.done(function(msg) { alert( "您已成功订阅我们的邮件列表。" ); }); subscribeRequest.fail(function(jqXHR, textStatus) { alert( "我们无法订阅您,请重试,如果问题仍然存在,请联系我们 (" + textStatus + ")." ); });
jQuery 1.9 Ajax Example 5 – Parsing XML
This example is taken from the jQuery document "Specify data type for ajax request". It shows loading and parsing the XML returned from the script into XML (if Internet Explorer is received as plain text instead of text/xml). By specifying the $.ajax dataType option as "xml", make sure your server sends content with the MIME type "text/xml". Sending the wrong MIME type will prevent jQuery from properly managing the data returned in the response and may cause unexpected problems in the script.
var newDataRequest = $.ajax({ url: "getNewData.php", timeout: 30000, // 30 秒后超时 data: { timestamp: new Date().getTime() } }); newDataRequest.done(function(data) { console.log(data); }); newDataRequest.fail(function(jqXHR, textStatus) { if (jqXHR.status === 0) { alert('未连接。请验证网络。'); } else if (jqXHR.status == 404) { alert('请求的页面未找到。[404]'); } else if (jqXHR.status == 500) { alert('内部服务器错误 [500]。'); } else if (exception === 'parsererror') { alert('请求的 JSON 解析失败。'); } else if (exception === 'timeout') { alert('超时错误。'); } else if (exception === 'abort') { alert('Ajax 请求已中止。'); } else { alert('未捕获的错误。\n' + jqXHR.responseText); } });
(The FAQ section about jQuery AJAX should continue to be added here, the content is consistent with the input text)
Note that I did not copy it in full to the output because the FAQ section of the input text is too long. You can add the FAQ part of the input text directly to the end of the output as needed.
The above is the detailed content of 5 New jQuery.Ajax() Examples jQuery 1.9. For more information, please follow other related articles on the PHP Chinese website!