Express框架与html之间如何进行数据传递
分类:
IT文章
•
2022-06-05 16:03:00
关于Node.js 的Express框架介绍,推荐看菜鸟教程的Express框架,很适合入门,这里不再赘述,这里主要讲一下Express框架与html之间如何进行数据传递
我采用的是JQuery的Ajax()向后台传参方式 (url传参)
1、Type属性为Get时:
(1)第一种方法:(通过url传参)
function GetQuery(id) {
if (id ==1||id==7) {
var name = "语文";
$.ajax({
url:"../ajaxHandler/ChartsHandler.ashx?>,
type: "get",
success: function (returnValue) {
$("#cId").val(returnValue);
},
error: function (returnValue) {
alert("对不起!数据加载失败!");
}
})
}
}
View Code
(2)第二种方法:(通过data传参)
function GetQuery(id) {
if (id ==1||id==7) {
var name = "语文";
$.ajax({
url:"../ajaxHandler/ChartsHandler.ashx",
type: "get",
//获取某个文本框的值
//data: ").val(),
data: "> name,
// 或者(注意:若参数为中文时,以下这种传参不会造成后台接收到的是乱码)
//data: {
// "id": id,
// "name": name
//},
success: function (returnValue) {
$("#cId").val(returnValue);
},
error: function (returnValue) {
alert("对不起!数据加载失败!");
}
})
}
}
View Code
(2)后台获取参数:(.ashx一般处理程序)
public void ProcessRequest(HttpContext context)
{
string 科目Id = context.Request.QueryString["id"];
string 科目名称 = context.Request.QueryString["name"];
}
View Code
2、Type属性为post时:
(1)第一种方法:(通过url传参)
function GetQuery(id) {
if (id ==1||id==7) {
var name = "语文";
$.ajax({
url:"../ajaxHandler/ChartsHandler.ashx?>,
type: "post",
success: function (returnValue) {
$("#cId").val(returnValue);
},
error: function (returnValue) {
alert("对不起!数据加载失败!");
}
})
}
}
View Code
function query(myData, successFunc, isAsync) {
$.ajax({
dataType: "json",
url: "http://localhost:8081/",
type: "POST",
data: {"y1":myData.getNorthWest().lng,"y2":myData.getSouthEast().lng,"x1":myData.getSouthEast().lat,"x2":myData.getNorthWest().lat},
async: isAsync,
success: successFunc,
error: function (xhr, status, error) {
console.log('Error: ' + error.message);
$('#lblResponse').html('Error connecting to the server.');
}
});
}
//此为部分代码,无关内容略去
let express = require('express');
let app = express();
let bodyParser = require('body-parser');
// 创建 application/x-www-form-urlencoded 编码解析
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.use(require('body-parser').urlencoded({limit: '5mb', extended: true}));
app.post('/',function(req,res,next) { //此处对应 url http://localhost:8081/ 如果是 http://localhost:8081/apple.htm 则应该是 app.get('/apple.htm',function(){……});
db.query(req.body,res,client); }); //req.body就是传来的data,上面的body-parser一定要添加