How to use native ajax and encapsulated ajax (with code)
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即可浏览
##3. index.json content
{ "items":"Express 是一个自身功能极简,完全是由路由和中间件构成一个的 web 开发框架:从本质上来说,一个 Express 应用就是在调用各种中间件。中间件(Middleware) 是一个函数,它可以访问请求对象(request object (req)), 响应对象(response object (res)), 和 web 应用中处于请求-响应循环流程中的中间件,一般被命名为 next 的变量。" }
4、index.html content
.content-box{ width: 400px; } #text{ padding: 0px 10px; width: 400px; height: 300px; }
5, html structure
<h3 id="这是一段不变的内容这是一段不变的内容这是一段不变的内容">这是一段不变的内容这是一段不变的内容这是一段不变的内容</h3> <p class="content-box"> <textarea id="text">如果要让用户留在当前页面中,同时发出新的HTTP请求,就必须用JavaScript发送这个新请求,接收到数据后,再用JavaScript更新页面,这样一来,用户就感觉自己仍然停留在当前页面,但是数据却可以不断地更新。</textarea> </p> <button id="btnchange">换一换</button>
6. Native ajax writing method
##
window.onload=function(){ function clickbtn(){ var request; if(window.XMLHttpRequest){ request=new XMLHttpRequest(); // 新建XMLHttpRequest对象 }else{ request=new ActiveXObject('Microsoft.XMLHTTP'); //兼容ie } request.open('GET','/ajax/index',true); request.onreadystatechange=function(){ // 状态发生变化时,函数被回调 if(request.readyState===4){ // 成功完成 if(request.status===200){ var text=request.responseText;//成功,通过responseText拿到响应的文本 document.getElementById('text').value=text; }else{ var err=fail(response.status);// 失败,根据响应码判断失败原因 alert(err); } }else{ // HTTP请求还在继续... } } // 最后调用send()方法才真正发送请求 request.send();//POST请求需要把body部分以字符串或者FormData对象传进去 } document.getElementById('btnchange').onclick=clickbtn; }
Or jquery writing
$(document).ready(function(){ $('#btnchange').click(function(){ $.ajax({ type:"GET", url:"/ajax/index", datatype:"json", success:function(data){ $('#text').val(data); } }); }); });
运行之后在浏览器输入localhost:3003即可浏览
# 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!
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!

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Linux new version
SublimeText3 Linux latest version

Atom editor mac version download
The most popular open source editor

SublimeText3 English version
Recommended: Win version, supports code prompts!