Home Web Front-end JS Tutorial 5 New jQuery.Ajax() Examples jQuery 1.9

5 New jQuery.Ajax() Examples jQuery 1.9

Feb 23, 2025 am 10:08 AM

5 New jQuery.Ajax() Examples jQuery 1.9

Summary of key points

  • The use of jQuery.Ajax() function has evolved in recent versions. The .done(), .fail() and .always() methods replace the deprecated jqXHR.success() and .error respectively. The () and .complete() methods.
  • This article provides five examples of jQuery.Ajax() usage. Example 1 demonstrates the basic Ajax request to subscribe to a newsletter, while Example 2 shows how to handle errors and timeouts for Ajax requests.
  • Example 3 illustrates how to use the dataFilter function to process the raw data returned by an Ajax request, while Example 4 discusses specifying the available content response header type on XMLHttpRequest.
  • The last example, Example 5, explains how to parse XML data returned from the script, emphasizes the importance of correctly specifying the $.ajax dataType option and ensuring that the server sends content with the appropriate MIME type.

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 + ")." );
});
Copy after login
Copy after login

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);
    }
});
Copy after login
Copy after login

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 + ")." );
});
Copy after login

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 + ")." );
});
Copy after login
Copy after login

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);
    }
});
Copy after login
Copy after login

(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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1659
14
PHP Tutorial
1258
29
C# Tutorial
1232
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles