Ajax基础教程

发布时间:2025-12-09 19:54:48 浏览次数:3

Ajax的实现步骤

1.创建Ajax对象

var xhr = new XMLHttpRequest();

2.告诉Ajax请求地址以及请求方式

xhr.open('get','http://www.example.com');

3.发送请求

xhr.send();

4.获取服务器端给与客户端的相应数据

xhr.onload = function () {console.log (xhr.responseText);}

5.example

<script type=" text/javascript">// 1.创建ajax对象var xhr = new XMLHttpRequest();//2.告诉Ajax对象要向哪发送请求,以什么方式发送请求//1)请求方式2)请求地址xhr.open('get','http://localhost:3000/first');// 3.发送请求xhr.send();//4.获取服务器端响应到客户端的数据xhr.onload = function (){console.log(xhr.responseText);}</script>

服务器端响应

框架

//引入express框架const express = require('express');//路径处理模块const path = require('path');//创建web服务器const app = express();//静态资源访问服务功能app.use(express.static(path.join(__dirname,'public')));//监听端口app.listen(3000);//控制台提示输出console.log('服务器启动成功');

处理服务器端返回的JSON数据

//引入express框架const express = require('express');//路径处理模块const path = require('path');//创建web服务器const app = express();//静态资源访问服务功能app.use(express.static(path.join(__dirname,'public')));//对应01html文件app.get('/first',(req,res) => {res.send('Hel1o, Ajax');});app.get('/responseData',(req,res) => {res.send({"name":"zs"});});//监听端口app.listen(3000);//控制台提示输出console.log('服务器启动成功'); xhr.onload = function (){//此时控制台输出的是字符串类型(而不是对象类型)//console.log(xhr.responseText);//需要将JSON字符串转换为JSON对象var responseText=JSON.parse(xhr.responseText )console.log(responseText) //输出为对象类型}

请求参数传递

GET请求方式

xhr.open('get','http://www.example.com?name=zhangsan&age=20");
  • 具体实现
//为按钮添加点击事件btn.onclick = function () {//创建ajax对象var xhr = new XMLHttpRequest();//获取用户在文本框中输入的值var nameValue = username.value;var ageValue = age.value;//拼接请求参数var params='username='+ nameValue +'&age='+ ageValue;//配置ajax对象xhr.open('get','http://localhost:3000/get?'+params );//发送请求xhr.send( );//获取服务器端响应的数据xhr.onload = function () { console.log( xhr.responseText)}}

POST请求方式

xhr.setRequestHeader('Content-Type",'application/x-www-form-urlencoded')xhr.send('name=zhangsan&age=20');
  • 具体实现
//为按钮添加点击事件btn.onclick = function () {//创建ajax对象var xhr = new XMLHttpRequest();//获取用户在文本框中输入的值var nameValue = username.value;var ageValue = age.value;//拼接请求参数var params='username='+ nameValue +'&age='+ ageValue;//配置ajax对象xhr.open('post','http://localhost:3000/post');//设置请求参数格式的类型(POST请求必须要设置)xhr.setRequestHeader('Content-Type",'application/x-www-form-urlencoded');//发送请求xhr.send(params);//获取服务器端响应的数据xhr.onload = function () { console.log(xhr.responseText)}}

请求参数的格式

JSON请求只能在POST中使用在请求头中指定Content-Type属性的值是application/json告诉服务器端当前请求参数的格式是json
  • 具体实现

    <script type="text/javascript">// 1.创建ajax对象var xhr = new XMLHttpRequest();// 2.告诉Ajax对象要向哪发送请求,以什么方式发送请求// 1)请求方式2)请求地址xhr.open('post','http://localhost:3000/json');//通过请求头告诉服务器端客户端向服务器端传递的请求参数的格式是什么xhr.setRequestHeader('Content-Type','application/json');//3.发送请求// JSON.stringify() 将json对象转换为json字符串xhr.send(JSON.stringify({name:'lisi',age:50}));//4.获取服务器端响应到客户端的数据xhr.onload = function (){console.log(xhr.responseText)}</script>
需要做网站?需要网络推广?欢迎咨询客户经理 13272073477