Table of Contents
CSS3 Animation
Home Web Front-end JS Tutorial 实例讲解使用原生JavaScript处理AJAX请求的方法_javascript技巧

实例讲解使用原生JavaScript处理AJAX请求的方法_javascript技巧

May 19, 2016 am 10:42 AM
ajax javascript

Ajax 是异步的JavaScript和XML的简称,是一种更新页面某部分的机制。它赋予了你从服务器获取数据后,更新页面某部分的权力,从而避免了刷新整个页面。另外,以此方式实现页面局部更新,不仅能有效地打造流畅的用户体验,而且减轻了服务器的负载。

下面是对一个基本的 Ajax 请求进行剖析:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'send-ajax-data.php');
xhr.send(null);
Copy after login

在这里, 我们创建了一个能向服务器发出 HTTP 请求的类的实例。然后调用其 open 方法,其中第一个参数是 HTTP 请求方法,第二个参数是请求页面的 URL。最后,我们调用参数为 null 的 send 方法。假如使用 POST 请求方法(这里我们使用了 GET),那么 send 方法 的参数应该包含任何你想发送的数据。

下面是我们如何处理服务器的响应:

xhr.onreadystatechange = function(){
 var DONE = 4; // readyState 4 代表已向服务器发送请求
 var OK = 200; // status 200 代表服务器返回成功
 if(xhr.readyState === DONE){
  if(xhr.status === OK){
   console.log(xhr.responseText); // 这是返回的文本
  } else{
   console.log("Error: "+ xhr.status); // 在此次请求中发生的错误
  }
 }
}
Copy after login

onreadystatechange 是异步的,那么这就意味着它将可在任何时候被调用。这种类型的函数被称为回调函数——一旦某些处理完成后,它就会被调用。在此案例中,这个处理发生在服务器。

示例

便捷的 Ajax 方法也是不少人依赖 jQuery 的原因,但实际上原生 JavaScript 的 Ajax api 也很强大,并且基本的使用在各个浏览器中的差异不大,因此完全可以自行封装一个 Ajax 对象,下面是封装好的 Ajax 对象:

// Ajax 方法
 
// 惰性载入创建 xhr 对象
 
function createXHR(){
 
 if ( 'XMLHttpRequest' in window ){
 
 
  createXHR = function(){
   return new XMLHttpRequest();
  };
 
 } else if( 'ActiveXObject' in window ){
 
  createXHR = function(){
 
   return new ActiveXObject("Msxml2.XMLHTTP");
  };
 
 } else {
 
  createXHR = function(){
   throw new Error("Ajax is not supported by this browser");
  };
 
 }
 
 return createXHR();
 
}
 
// Ajax 执行
 
function request(ajaxData){
 
 var xhr = createXHR();
 
 ajaxData.before && ajaxData.before();
 
 // 通过事件来处理异步请求
 xhr.onreadystatechange = function(){
 
  if( xhr.readyState == 4 ){
 
   if( xhr.status == 200 ){
 
    if( ajaxData.dataType == 'json' ){
 
     // 获取服务器返回的 json 对象
     jsonStr = xhr.responseText;
     json1 = eval('(' + jsonStr + ')'),
     json2 = (new Function('return ' + jsonStr))();
     ajaxData.callback(json2);
     // ajaxData.callback(JSON.parse(xhr.responseText)); // 原生方法,IE6/7 不支持
 
    } else
 
     ajaxData.callback(xhr.responseText);
 
   } else {
 
    ajaxData.error && ajaxData.error(xhr.responseText);
   }
  }
 };
 
 // 设置请求参数
 xhr.open(ajaxData.type, ajaxData.url);
 
 if( ajaxData.noCache == true ) xhr.setRequestHeader('If-Modified-Since', '0');
 
 if( ajaxData.data ){
 
  xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
  xhr.send( ajaxData.data );
 
 } else {
? ?  
  xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  xhr.send( null );
 }
 
 return xhr;
}
 
function post(ajaxData){
 
 ajaxData.type = 'POST';
 
 var _result = request(ajaxData);
 
 return _result;
}
 
function get(ajaxData){
 
 ajaxData.type = 'GET';
 
 ajaxData.data = null;
 
 var _result = request(ajaxData);
 
 return _result;
}
Copy after login

下面给出一个使用例子:

index.html

<!DOCTYPE HTML>
<html lang="zh-CN">
<head>
 <meta charset="UTF-8">
 <title>原生 JavaScript 实现 Ajax</title>
 <link rel="stylesheet" type="text/css" media="all" href="./common/common.css" />
 <style>
  #content {text-align: center; font-family: 'lucida Grande', 'Microsoft Yahei'}
  #content .btn_ctr {display: block; width: 120px; height: 30px; margin: 0 auto 20px; background: #53a7bb; color: #fff; font-weight: bold; font-size: 14px; line-height: 30px; text-decoration: none;
   border-radius: 4px;
  }
  #test {width: 280px; height: 130px; margin: 0 auto; padding: 15px; background: #fff; border-radius: 4px; text-align: left; }
 </style>
</head>
<body>
 
 <div id="header">
  <div id="header-content">
   <div id="header-inside">
    <p class="go-to-article"><a href="http://kayosite.com/css3-animation.html" title="打开原文" target="_blank" >Back To Article</a></p>
    <p class="go-to-blog"><a href="http://kayosite.com" title="进入我的博客 Kayo's Melody" target="_blank" >My Blog</a></p>
    <p class="copyright">Demo By Kayo &copy; Copyright 2011-2013</p>
   </div>
   <h1 id="CSS-Animation">CSS3 Animation</h1>
  </div>
 </div>
 
 <div id="content">
  <a class="btn_ctr" href="javascript:;" onclick="get({url: './ajax.html', callback: function(out){document.getElementById('test').innerHTML = out;}})">Ajax 获取内容</a>
 
  <div id="test"></div>
 </div>
  
 <script>
  // Ajax 方法,这里不在重复列出
 </script>
</body>
</html>

Copy after login
ajax.html
<!DOCTYPE HTML>
<html lang="zh-CN">
<head>
 <meta charset="UTF-8">
 <title>ajax</title>
</head>
<body>
 <p>成功获取到这段文本</p>
</body>
</html>
Copy after login

具体的效果可以浏览完整 Demo 。


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)

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

PHP vs. Ajax: Solutions for creating dynamically loaded content PHP vs. Ajax: Solutions for creating dynamically loaded content Jun 06, 2024 pm 01:12 PM

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

PHP and Ajax: Ways to Improve Ajax Security PHP and Ajax: Ways to Improve Ajax Security Jun 01, 2024 am 09:34 AM

In order to improve Ajax security, there are several methods: CSRF protection: generate a token and send it to the client, add it to the server side in the request for verification. XSS protection: Use htmlspecialchars() to filter input to prevent malicious script injection. Content-Security-Policy header: Restrict the loading of malicious resources and specify the sources from which scripts and style sheets are allowed to be loaded. Validate server-side input: Validate input received from Ajax requests to prevent attackers from exploiting input vulnerabilities. Use secure Ajax libraries: Take advantage of automatic CSRF protection modules provided by libraries such as jQuery.

Asynchronous data exchange using Ajax functions Asynchronous data exchange using Ajax functions Jan 26, 2024 am 09:41 AM

How to use Ajax functions to achieve asynchronous data interaction With the development of the Internet and Web technology, data interaction between the front end and the back end has become very important. Traditional data interaction methods, such as page refresh and form submission, can no longer meet user needs. Ajax (Asynchronous JavaScript and XML) has become an important tool for asynchronous data interaction. Ajax enables the web to use JavaScript and the XMLHttpRequest object

See all articles