今天除了登錄,還想做注冊,也不用form表單了,用jquery的ajax方法
1.數(shù)據(jù)格式
首先還是需要一個json文件,不需要很多數(shù)據(jù)
{"user":[{"name":"斯忒諾","password":"1"}]}
2.主界面body部分
<body>
用戶:<input type="text" id="name" value=""><br>
密碼:<input type="text" id="password" value=""><br>
<button id="register" onclick="re_click()">注冊</button>
<button id="log" onclick="log_click()">登錄</button>
</body>
3.數(shù)據(jù)傳遞
首先需要從前端傳遞用戶輸入的數(shù)據(jù),使用jquery的ajax方法,使用了get的傳遞方式
$.ajax(
{
url:"/user",
type: 'get',
data:{act:"reg",name:na,password:pa},
success:function(data)
{
data=JSON.parse(data)
//因?yàn)閭鬟f的數(shù)據(jù)是字符串格式的需要改為object
if(data.ok=="true")
{
alert("注冊成功")
}
else
{
alert("注冊失?。?+data.msg)
}
},
error:function()
{
alert("通信失敗")
}
})
那么從后端傳遞數(shù)據(jù),需要使用response.write(),把數(shù)據(jù)傳遞到前端,并使用success的回調(diào)函數(shù),將數(shù)據(jù)轉(zhuǎn)換為JSON格式并進(jìn)行判斷處理,傳遞的數(shù)據(jù)有兩個值,OK以及msg記錄是否成功以及原因,比如
res.write('{"ok":"false","msg":"此用戶已存在"}')
4.json文件讀取與增加
fs.readFile("username.json",function(err,data){
if(err)
{
req.write("404")
}
else {
var params={"name":get.name,"password":get.password}
//增添的項(xiàng)目由注冊時(shí)用戶填寫的內(nèi)容決定,以json中的格式記錄下來
var person = data.toString();
person = JSON.parse(person)
//將json中已經(jīng)有的數(shù)據(jù)取出來,因?yàn)槭且远M(jìn)制傳輸?shù)?,所以首先需要轉(zhuǎn)換為字符串,然后轉(zhuǎn)換為JSON
person.user.push(params)
//將傳來的對象push進(jìn)對象中
console.log("person.user",person.user)
var str = JSON.stringify(person)
//因?yàn)閚odejs的寫入文件只認(rèn)識字符串或者二進(jìn)制數(shù),所以把json對象轉(zhuǎn)換成字符串重新寫入json文件中
fs.writeFile("username.json",str,function(err)
{
if(err)
console.log(error)
else {
res.write('{"ok":"true","msg":"注冊成功"}')
}
res.end()
})
}
})
5.其余部分
沒什么重要的部分了,只有req.end()和fs.readFile()的異步很容易出錯,所以在每一個步驟中都單獨(dú)加入req.end(),雖然會變多,但是不會出錯。
res.write()除了在頁面中增加內(nèi)容,也有傳遞數(shù)據(jù)的作用