Home Web Front-end JS Tutorial How to use native ajax and encapsulated ajax (with code)

How to use native ajax and encapsulated ajax (with code)

Mar 31, 2018 am 11:47 AM
ajax Instructions Native

This time I will bring you how to use native ajax and encapsulated ajax (with code). What are the precautions for using native ajax and encapsulated ajax? The following is a practical case, let’s take a look .

When we don't know how to write a backend interface to test ajax, we can use the node environment to simulate a backend interface.

1. To simulate the back-end interface, you can refer to the small example of website development. Open the command window and go to the project folder and enter npm install express in the command line. --save, install expressmiddleware.

#2. Replace the content of app.js with


var express=require('express');
//var path=require('path');
var app=express();
 
//app.set('view',path.join(dirname,'views')); //在views目录下搜索所有模板
app.engine('html',require('ejs').express); //让ejs能够识别后缀为'.html'的文件 or app.engine("html",require("ejs").renderFile);
app.set('view engine','html');//在调用render函数时能自动为我们加上'.html' 后缀。如果没有第二句,我们就得把res.render(‘users')写成res.render(‘users.html'),否则会报错
 
var service=require('./webService/service.js');
 
app.use('/public',express.static('public'));
 
app.get('/',function(req,res){ //路由HTTP GET请求到有特殊回调的特殊路径。
 res.render('index');
});
 
app.get('/ajax/index',function(req,res){ //创建了一个模拟后端接口
 res.send(service.get_index_data());
});
 
/*若路径找不到,都返回404报错页面*/
app.use(function(req,res,next){
 var err=new Error('this page Not found');
 err.status=404;
 next(err);
});
 
app.listen(3003); //在浏览器输入localhost:3003即可浏览
Copy after login


##3. index.json content


{
 "items":"Express 是一个自身功能极简,完全是由路由和中间件构成一个的 web 开发框架:从本质上来说,一个 Express 应用就是在调用各种中间件。中间件(Middleware) 是一个函数,它可以访问请求对象(request object (req)), 响应对象(response object (res)), 和 web 应用中处于请求-响应循环流程中的中间件,一般被命名为 next 的变量。"
} 
Copy after login


4、index.html content


.content-box{
 width: 400px;
}
#text{
 padding: 0px 10px;
 width: 400px;
 height: 300px;
}
Copy after login


5, html structure


<h3>这是一段不变的内容这是一段不变的内容这是一段不变的内容</h3>
<p class="content-box">
 <textarea id="text">如果要让用户留在当前页面中,同时发出新的HTTP请求,就必须用JavaScript发送这个新请求,接收到数据后,再用JavaScript更新页面,这样一来,用户就感觉自己仍然停留在当前页面,但是数据却可以不断地更新。</textarea>
</p>
<button id="btnchange">换一换</button>
Copy after login


6. Native ajax writing method

##

window.onload=function(){
 function clickbtn(){
  var request;
  if(window.XMLHttpRequest){
   request=new XMLHttpRequest(); // 新建XMLHttpRequest对象
  }else{
   request=new ActiveXObject(&#39;Microsoft.XMLHTTP&#39;); //兼容ie
  }
  request.open(&#39;GET&#39;,&#39;/ajax/index&#39;,true);
  request.onreadystatechange=function(){ // 状态发生变化时,函数被回调
   if(request.readyState===4){ // 成功完成
    if(request.status===200){
     var text=request.responseText;//成功,通过responseText拿到响应的文本
     document.getElementById(&#39;text&#39;).value=text;
    }else{
     var err=fail(response.status);// 失败,根据响应码判断失败原因
     alert(err);
    }
   }else{
    // HTTP请求还在继续...
   }
  }
  // 最后调用send()方法才真正发送请求
  request.send();//POST请求需要把body部分以字符串或者FormData对象传进去
 }
 document.getElementById(&#39;btnchange&#39;).onclick=clickbtn;
}
Copy after login


Or jquery writing

$(document).ready(function(){
 $(&#39;#btnchange&#39;).click(function(){
  $.ajax({
   type:"GET",
   url:"/ajax/index",
   datatype:"json",
   success:function(data){
    $(&#39;#text&#39;).val(data);
   }
  });
 });
});
Copy after login


##
运行之后在浏览器输入localhost:3003即可浏览
Copy after login



# I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Ajax method to implement Form form submission


Detailed explanation of basic knowledge of HTTP messages and ajax


The above is the detailed content of How to use native ajax and encapsulated ajax (with code). 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)

How to use DirectX repair tool? Detailed usage of DirectX repair tool How to use DirectX repair tool? Detailed usage of DirectX repair tool Mar 15, 2024 am 08:31 AM

The DirectX repair tool is a professional system tool. Its main function is to detect the DirectX status of the current system. If an abnormality is found, it can be repaired directly. There may be many users who don’t know how to use the DirectX repair tool. Let’s take a look at the detailed tutorial below. 1. Use repair tool software to perform repair detection. 2. If it prompts that there is an abnormal problem in the C++ component after the repair is completed, please click the Cancel button, and then click the Tools menu bar. 3. Click the Options button, select the extension, and click the Start Extension button. 4. After the expansion is completed, re-detect and repair it. 5. If the problem is still not solved after the repair tool operation is completed, you can try to uninstall and reinstall the program that reported the error.

Introduction to HTTP 525 status code: explore its definition and application Introduction to HTTP 525 status code: explore its definition and application Feb 18, 2024 pm 10:12 PM

Introduction to HTTP 525 status code: Understand its definition and usage HTTP (HypertextTransferProtocol) 525 status code means that an error occurred on the server during the SSL handshake, resulting in the inability to establish a secure connection. The server returns this status code when an error occurs during the Transport Layer Security (TLS) handshake. This status code falls into the server error category and usually indicates a server configuration or setup problem. When the client tries to connect to the server via HTTPS, the server has no

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 use Baidu Netdisk-How to use Baidu Netdisk How to use Baidu Netdisk-How to use Baidu Netdisk Mar 04, 2024 pm 09:28 PM

Many friends still don’t know how to use Baidu Netdisk, so the editor will explain how to use Baidu Netdisk below. If you are in need, hurry up and take a look. I believe it will be helpful to everyone. Step 1: Log in directly after installing Baidu Netdisk (as shown in the picture); Step 2: Then select "My Sharing" and "Transfer List" according to the page prompts (as shown in the picture); Step 3: In "Friend Sharing", you can share pictures and files directly with friends (as shown in the picture); Step 4: Then select "Share" and then select computer files or network disk files (as shown in the picture); Fifth Step 1: Then you can find friends (as shown in the picture); Step 6: You can also find the functions you need in the "Function Treasure Box" (as shown in the picture). The above is the editor’s opinion

How to use potplayer-How to use potplayer How to use potplayer-How to use potplayer Mar 04, 2024 pm 06:10 PM

Potplayer is a very powerful media player, but many friends still don’t know how to use potplayer. Today I will introduce how to use potplayer in detail, hoping to help everyone. 1. PotPlayer shortcut keys. The default common shortcut keys for PotPlayer player are as follows: (1) Play/pause: space (2) Volume: mouse wheel, up and down arrow keys (3) forward/backward: left and right arrow keys (4) bookmark: P- Add bookmarks, H-view bookmarks (5) full screen/restore: Enter (6) multiple speeds: C-accelerate, 7) Previous/next frame: D/

What is the KMS activation tool? How to use the KMS activation tool? How to use KMS activation tool? What is the KMS activation tool? How to use the KMS activation tool? How to use KMS activation tool? Mar 18, 2024 am 11:07 AM

The KMS Activation Tool is a software tool used to activate Microsoft Windows and Office products. KMS is the abbreviation of KeyManagementService, which is key management service. The KMS activation tool simulates the functions of the KMS server so that the computer can connect to the virtual KMS server to activate Windows and Office products. The KMS activation tool is small in size and powerful in function. It can be permanently activated with one click. It can activate any version of the window system and any version of Office software without being connected to the Internet. It is currently the most successful and frequently updated Windows activation tool. Today I will introduce it Let me introduce to you the kms activation work

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

How to merge cells using shortcut keys How to merge cells using shortcut keys Feb 26, 2024 am 10:27 AM

How to use the shortcut keys for merging cells In daily work, we often need to edit and format tables. Merging cells is a common operation that can merge multiple adjacent cells into one cell to improve the beauty of the table and the information display effect. In mainstream spreadsheet software such as Microsoft Excel and Google Sheets, the operation of merging cells is very simple and can be achieved through shortcut keys. The following will introduce the shortcut key usage for merging cells in these two software. exist

See all articles