前端通过ajax get或则post方式提交数据到后台,后台传递数据到前台互相调用
getjson.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>postjson提交</title>
<!--引入jquery包-->
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
/*用于按钮触发ajax*/
function sub(){
$.ajax({
/*ajax属性,get方式可以直接在url进行拼接*/
type:"GET",
/*传递过去的值*/
url:"http://localhost:3000?name=jw&&age=18",
success:function(res){
/*输出返回的值*/
console.log(res);
}
})
}
</script>
</head>
<body>
<button onclick="sub()">getjson请求</button>
</body>
</html>
getjson.js
var express=require("express");//导入express
var app = express();//实例化
app.use(express.static("static"));//静态内容
app.all('*',function(req,res,next){//跨域问题
res.setHeader("Access-Control-Allow-Origin", "*");
next();
});
app.get("/",function(req,res){
console.log(req.query);//获取前端ajax传递过来的信息并输出
res.send({//返回信息给前端
"msg":"返回数据"
})
}).listen(3000);
postjson.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>postjson提交</title>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
function bus() {
$.ajax({
type:"POST",
url:"http://localhost:3000/post",
data:{
name:"jw",
age:18,
},
success:function(res){
console.log(res);
}
})
}
</script>
</head>
<body>
<button onclick="bus()">postjson提交</button>
</body>
</html>
postjson.js
var express = require("express");
var app = express();//
var bodyParser = require("body-parser");//使用插件,用于解析/post
app.use(express.static("static"));//加载项目静态内容
app.all('*', function (req, res, next) {//设置跨域问题
res.setHeader("Access-Control-Allow-Origin", "*");
next();
});
app.use(bodyParser.urlencoded({extended: false}));//解析字符
app.post("/post", function (req, res) {
console.log(req.body);//获取前端ajax提交的数据
res.send({
"msg":"post",
"code":1
})
}).listen(3000);