html间数据传送,Express框架与html之间如何进行数据传递(示例代码)
關于Node.js 的Express框架介紹,推薦看菜鳥教程的Express框架,很適合入門,這里不再贅述,這里主要講一下Express框架與html之間如何進行數據傳遞
我采用的是JQuery的Ajax()向后臺傳參方式(url傳參)
1、Type屬性為Get時:
(1)第一種方法:(通過url傳參)
functionGetQuery(id) {if (id ==1||id==7) {var name = "語文";
$.ajax({
url:"../ajaxHandler/ChartsHandler.ashx?id="+id+"&name="+name +"",
type:"get",
success:function(returnValue) {
$("#cId").val(returnValue);
},
error:function(returnValue) {
alert("對不起!數據加載失敗!");
}
})
}
}
View Code
(2)第二種方法:(通過data傳參)
functionGetQuery(id) {if (id ==1||id==7) {var name = "語文";
$.ajax({
url:"../ajaxHandler/ChartsHandler.ashx",
type:"get",//獲取某個文本框的值
//data: "id=" + id + "&name=" + $("#name").val(),
data: "id=" + id + "&name=" +name,//或者(注意:若參數為中文時,以下這種傳參不會造成后臺接收到的是亂碼)
//data: {
//"id": id,
//"name": name
//},
success: function(returnValue) {
$("#cId").val(returnValue);
},
error:function(returnValue) {
alert("對不起!數據加載失敗!");
}
})
}
}
View Code
(2)后臺獲取參數:(.ashx一般處理程序)
public voidProcessRequest(HttpContext context)
{
string 科目Id= context.Request.QueryString["id"];
string 科目名稱= context.Request.QueryString["name"];
}
View Code
2、Type屬性為post時:
(1)第一種方法:(通過url傳參)
functionGetQuery(id) {if (id ==1||id==7) {var name = "語文";
$.ajax({
url:"../ajaxHandler/ChartsHandler.ashx?id="+id+"&name="+name +"",
type:"post",
success:function(returnValue) {
$("#cId").val(returnValue);
},
error:function(returnValue) {
alert("對不起!數據加載失敗!");
}
})
}
}
View Code
能看到無論是post還是get它們的方法都大同小異,ajax中傳遞的參數不止這些,還可以有很多具體參見博客http://blog.csdn.net/ailo555/article/details/48577721
二、接下來說一下express框架和ajax
我采用的是“通過url傳參”,dataType為“json”
具體示例如下:
functionquery(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) { //此處對應 urlhttp://localhost:8081/ 如果是 http://localhost:8081/apple.htm 則應該是 app.get(‘/apple.htm‘,function(){……});
db.query(req.body,res,client); }); //req.body就是傳來的data,上面的body-parser一定要添加
總結
以上是生活随笔為你收集整理的html间数据传送,Express框架与html之间如何进行数据传递(示例代码)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MyEclipse设置字体大小
- 下一篇: 微信语音保存教程