今天除了登錄惹资,還想做注冊贺纲,也不用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)
//因為傳遞的數(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格式并進行判斷處理,傳遞的數(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}
//增添的項目由注冊時用戶填寫的內(nèi)容決定,以json中的格式記錄下來
var person = data.toString();
person = JSON.parse(person)
//將json中已經(jīng)有的數(shù)據(jù)取出來庵佣,因為是以二進制傳輸?shù)那附海允紫刃枰D(zhuǎn)換為字符串,然后轉(zhuǎn)換為JSON
person.user.push(params)
//將傳來的對象push進對象中
console.log("person.user",person.user)
var str = JSON.stringify(person)
//因為nodejs的寫入文件只認識字符串或者二進制數(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()的異步很容易出錯,所以在每一個步驟中都單獨加入req.end()肛根,雖然會變多辫塌,但是不會出錯。
res.write()除了在頁面中增加內(nèi)容派哲,也有傳遞數(shù)據(jù)的作用