ajax的封装

it2023-10-16  64

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> //考虑向后台传递参数的问题 /* 1.如果是post请求方式就要向send传递参数, 如果是get就要参数直接拼接在url路径的后面 */ function ajax(options){ let params = '' //拼接传递过来的值 //创建一个xhr对象 let xhr = new XMLHttpRequest(); //把传过来的JSON值拼接成字符串 for(let attr in options.data){ params += attr +'='+options.data[attr]+'&' } //拼接之后有一点小的bug字符串后面会多一个&,所以我们要切割出去 params = params.substr(0,params.length-1); //判断传递过来的类型是get还是post我们好传递参数 if(options.type == 'get'){ options.url = options.url+'?'+params } //配置ajax对象 xhr.open(options.type,options.url); //post请求方式的判断 if(options.type == 'post'){ //如果是post请求方式我们就必须设置请求头 //但是这里也有一个问题,如果我们的请求数据格式不是urlencoded而是json那 //所以进行判断 let contentType = '';//用来保存数据格式 if(options.header['Content-Type']=='application/x-www-form-urlencoded'){ contentType = 'application/x-www-form-urlencoded' xhr.setRequestHeader('Content-Type',contentType) xhr.send(params) }else{ contentType = 'application/json' xhr.setRequestHeader('Content-Type',contentType) xhr.send(JSON.stringify(options.data)) } console.log(contentType); }else{ xhr.send() } //接收数据 xhr.onload = function(){ options.success(xhr.responseText) } } ajax({ type:'post', url:'http://localhost:5000/first', data:{ name:'李权', age:'20' }, header:{'Content-Type':'application/json'}, success:function(data){ alert(data) } } ) </script> </body> </html>

 

最新回复(0)