文章目录
- ajax、FormData、fetch的使用
-
- 本地使用Nodejs模拟服务器响应
- XMLHttpRequest实现ajax请求
- jquery实现ajax请求
- fetch实现ajax请求
- formData
ajax、FormData、fetch的使用
本地使用Nodejs模拟服务器响应
使用nodejs简单实现服务器响应ajax请求,返回json数据,
注意:
ajax存在请求跨域问题,主要是因为浏览器响应机制,只会响应同一个域名下的文件,默认不同域的响应会忽略处理,因此需要再服务器设置响应头中设置相关配置
- nodejs中设置
res.setHeader('Access-Control-Allow-Origin','*');res.setHeader('Access-Control-Allow-Headers',"x-requested-with, content-type");
- php中设置
header("Access-Control-Allow-Origin:*");header('Access-Control-Allow-Methods:POST');header('Access-Control-Allow-Headers:x-requested-with, content-type');
代码实现:
const http = require('http');
const multiparty = require('multiparty');http.createServer((req,res)=>{
res.setHeader('Access-Control-Allow-Origin','*');res.write(JSON.stringify({
code:200,msg:"sucess"}));res.end();
}).listen(8888,()=>{
console.log('Server 8888 running');
})http.createServer((req,res)=>{
res.setHeader('Access-Control-Allow-Origin','*');res.setHeader('Access-Control-Allow-Headers',"x-requested-with, content-type");let option = {
autoFiles:true,uploadDir:'./20191226/upload'}let form = new multiparty.Form(option);form.parse(req);form.on('field',(name,value)=>{
console.log("field:",name,value);})form.on('file',(name,file)=>{
console.log("file:",name,file);})form.on("close",()=>{
console.log('upload completed');res.write(JSON.stringify({
code:200,msg:"sucess"}));res.end();})form.on("error",(err)=>{
console.log('upload error');res.write(JSON.stringify({
code:200,msg:err}));res.end();})}).listen(8888,()=>{
console.log('Server 8888 running');
})
XMLHttpRequest实现ajax请求
代码实现:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title><script>window.onload = ()=>{
let btn = document.getElementById('btn');btn.onclick = ()=>{
let xhr = new XMLHttpRequest();xhr.open('GET','http://127.0.0.1:8888',true);//第三个参数默认为true异步请求,false为同步请求,目前已废弃xhr.send();//发送请求,如果为POST提交时,可以通过send()参数进行发送xhr.onreadystatechange = ()=>{
if(xhr.readyState==4){
//已成功发送请求if(xhr.status>=200&&xhr.status<300||xhr.status==304){
// alert("请求成功");let result = JSON.parse(xhr.responseText);console.log(result) }else{
alert("请求失败!");}}}}}</script></head>
<body><input type="button" value="ajax请求测试" id="btn">
</body></html>
jquery实现ajax请求
jquery中提供多种发起ajax请求的方式,常用有 . a j a x 、 .ajax、 .ajax、.post、$.get方式
代码实现:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title><script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script><script>$(function(){
$(document).on('click','#btn',()=>{
let list = {
};$.ajax({
type:"POST",//请求方式contentType:"application/json;charset=UTF-8",//请求类型url:"http://127.0.0.1:8888",//请求地址data:JSON.stringify(list),//请求数据success:result=>{
console.log(JSON.parse(result));return JSON.parse(result);},//请求成功error:err=>{
console.log(err.status);console.log(err.responseText);}});})})</script>
</head>
<body><input type="button" value="ajax请求测试" id="btn">
</body></html>
fetch实现ajax请求
ES6中新增,用法简单
代码实现
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title><script>window.onload = ()=>{
let btn = document.getElementById('btn');btn.onclick = ()=>{
var req = new Request("http://127.0.0.1:8888",{
method:'POST',cache:'reload'});fetch(req).then(response=>{
return response.json();}).then(data=>{
console.log(data);}).catch(err=>{
console.log(err);})}}</script>
</head>
<body><input type="button" value="ajax请求测试" id="btn">
</body></html>
formData
代码实现
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title><script>window.onload = function(){
let myForm = document.getElementById('myForm'); myForm.onsubmit = function(){
let formData = new FormData(myForm);let xhr =new XMLHttpRequest();xhr.open(myForm.method,myForm.action,true);xhr.send(formData);xhr.onreadystatechange = ()=>{
if(xhr.readyState==4){
//已成功发送请求if(xhr.status>=200&&xhr.status<300||xhr.status==304){
alert("请求成功");let result = JSON.parse(xhr.responseText);console.log(result) }else{
alert("请求失败!");}}}return false;}}</script> </head>
<body><form id="myForm" action="http://127.0.0.1:8888" method="POST" enctype="multipart/form-data">姓 名:<input type="text" name="username"><br>密 码:<input type="password" name="password"><br>附 件:<input type="file" name="file" id=""><br><input type="submit" value="ajax请求测试" id="btn"></form>
</body></html>