ajax小实践

本文介绍了如何使用Ajax进行批量员工信息查询,通过给定的HTTP接口,传入员工ID获取详细信息,并探讨了CORS跨域问题。此外,还展示了如何在原生JS中实现文件上传并显示进度条的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、传值取数据

给定一个http接口,传入一个员工id,返回员工的详细信息,接口形式为 http://localhost/query?id=。要求在前端实现一个根据一批员工id,通过 ajax 查询员工信息的功能。(阿里笔试题)

客户端:

<!DOCTYPE html>  
<html>  
<head>  
    <meta charset="utf-8">  
    <meta http-equiv="X-UA-Compatible" content="IE=edge">  
    <title>聊天</title>  
    <link rel="stylesheet" href="">
    <style type="text/css">  
		
	</style>
</head>  

  
<body>  
    <input id="gett" type="button" />
    <div id="data">here's the data</div>
    <script type="text/javascript">
		var btn=document.getElementById("gett");
		btn.onclick=function(){
			var staff=[1,2,3,4,5,6,7,8],ul=document.createElement("ul");
			staff.forEach(function(index,element,array){
				if(XMLHttpRequest){
					var xhr=new XMLHttpRequest(),url="http://localhost:3000/query?id="+element;
					xhr.open("get",url,true);
					// xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
					xhr.onreadystatechange=function(){
						if(xhr.status >=200&&xhr.status<300 || xhr.status==304){
								if(xhr.readyState==4){
									ul.innerHTML+='<li>'+element+":"+xhr.responseText+'</li>';
								}
								else{
									console.log("error");
									console.log(xhr.status);
								}
						}
					};
					xhr.send(null)
					// (1)xmlhttp的send是传递参数用的,但是只有在使用post方式提交请求的时候才有用  
					// 	如下:  
					// 	xmlhttp.open("post",url,true);   
					// 	xmlhttp.send(url);  
					//  (2)用get的话一般就是:  
					// 	xmlhttp.open("get",url,true);   
					// 	xmlhttp.send(null);  
				}
			});
			var main=document.getElementById("data");
			main.appendChild(ul);
		};
	</script>      
</body>  
  
</html> 

服务器端:

var express=require("express");
var app=express();
/*app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});*/
app.get('/query',function(req,res){
	res.header("Access-Control-Allow-Origin", "*");
	var url=req.url;
	var id=url.substring(url.indexOf('=')+1);
	res.send(id);
});
app.use(express.static(__dirname));
app.listen(3000);

注释的那一段是百度到的CORS跨域要加的head头,也着实体验了一把跨域确实会出现问题(先运行js,服务端工作属于localhost,再单纯用浏览器打开html文件属于[文件路径。。。];

标题二尚有错误,保存下思路待续orz

二、实现文件上传并显示进度条(原生js)

客户端

<!DOCTYPE html>  
<html>  
<head>  
    <meta charset="utf-8">  
    <meta http-equiv="X-UA-Compatible" content="IE=edge">  
    <title>聊天</title>  
    <link rel="stylesheet" href="">
    <style type="text/css">  
		#progress {
	        height: 10px;
	        width: 300px;
	        border: 1px solid gold;
	        position: relative;
	        border-radius: 5px;
	        display: inline-block;
    	}
    
	    #progress .progress-item {
	        height: 100%;
	        position: absolute;
	        left: 0;
	        top: 0;
	        background: chartreuse;
	        border-radius: 5px;
	        transition: width .3s linear;
	    }
	</style>
</head>  

  
<body>  
     <div id="progress">
        <div class="progress-item"></div>
    </div>
    <form class="form-horizontal" enctype='multipart/form-data' method='post' action='https://localhost:3000'>
        	<input type="file" id="filess"/>
        	<button onclick="handle()">上传</button>

     </form>
    <script>
    	function handle(){
    		let file=document.getElementById("filess").files[0];
    		let upfile=new FormData();
    		upfile.append("avator",file);
    		var xhr = new XMLHttpRequest();
			var url="localhost:3000/"
		    xhr.open('POST', url);
		    // 上传完成后的回调函数
		    xhr.onreadystatechange = function() {
		        if (xhr.status === 200&&xhr.readyState==4) {  
		            console.log(xhr.responseText);
		        } else { 
		            console.log('上传出错');
		        }
		    };
		    // 获取上传进度
		    xhr.upload.onprogress = function(event) {
		        console.log(event.loaded)
		        console.log(event.total)
		        if (event.lengthComputable) {
		            var percent = Math.floor(event.loaded / event.total * 100);
		            document.querySelector("#progress .progress-item").style.width = percent + "%";
		            // 设置进度显示
		            console.log(percent)
		        }
		    };
		    xhr.send(upfile);
	    }	
	</script>      
</body>  
  
</html> 


服务端


const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express();
 
//所有请求过来,都去项目当前的public目录下寻找所请求的文件,找到就返回
app.use(express.static(__dirname));
 
//选择diskStorage存储
const storage = multer.diskStorage({
 destination: function (req, file, cb) {
  cb(null, path.resolve('uploads'));
 },
 filename: function (req, file, cb) {
  cb(null, Date.now() + path.extname(file.originalname));//增加了文件的扩展名
 }
});
 
const upload = multer({storage: storage});
 
app.post('/', upload.single('avatar'), function(req, res, next) {
 
 res.send({
  err: null,
  //filePath:就是图片在项目中的存放路径
  filePath: 'uploads/' + path.basename(req.file.path)
 });
});
 
app.listen(3000, function () {
 console.log("app is listening 3000 port");
});



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值