2017-10-18 83 views
0

我有一個註冊表單的網頁。我需要將表單中輸入的數據存儲到json文件中,以便在登錄時使用它。如何將數據附加到使用JavaScript和Ajax的json文件?

我沒有使用任何網絡服務器。我在瀏覽器中運行。 我試過小ajax,但它給了我錯誤。

我的JSON文件(file.json)

var details = [{ 
"username" : "[email protected]", 
"password" : "1234" 
}, 
{ 
"username" : "[email protected]", 
"password" : "12345" 
}] 

的JavaScript:

function signup() 
{ 

    var username = document.getElementById("uname").value; 
    var password = document.getElementById("psw").value; 
    var xhttp = new XMLHttpRequest(); 
var data = "username=username&password=password"; 
    xhttp.open("POST", "file.json", true); 
    xhttp.send(data); 
} 

我的HTML

<!DOCTYPE html> 
<html> 
<title>Signup</title> 
<script type="text/javascript" src="script.js"></script> 
<script type="text/javascript" src="file.json"></script> 
<body> 

<h2 style="text-align:center;">Signup Form</h2> 
    <div style="width:800px; margin:0 auto;border: 5px solid #f1f1f1;"> 
    <form action="Javascript:signup();" style="padding-left:85px;"> 
    <label><b>&nbspEmail id :</b></label> 
    <input type="text" placeholder="Enter Email" id="uname" required;> 
    <label><b>&nbsp&nbsp&nbsp&nbspYour Full Name :</b></label> 
    <input type="text" placeholder="Enter Name" id="name" required;><br> 
    </div> 
     <div style="width:716px; margin:0 auto;border: 5px solid #f1f1f1;padding-left:85px"> 
    <label><b>Password:</b></label> 
    <input type="password" placeholder="Enter Password" id="psw" required> 
    <label><b>Re-enter Password:</b></label> 
    <input type="password" placeholder="Re-Enter Password" id="pswc" required onkeyup="passcheck(this.value);"><br> 
    </div> 
     <div style="margin:0 auto;padding-left:600px"> 
    <button type="submit" >Signup</button><br> 
     <a href="login.html">Login now</a> 
    </form> 
    </div> 
<div style="text-align:center;" id="error"></div> 

</body> 
</html> 

當我運行這段代碼,檢查控制檯,我得到的錯誤說:

Failed to load file:///C:/Users/Victor/Documents/login%20js/file.json: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. 

需要做些什麼才能將我的新用戶數據存儲到file.json中?

+0

你不能從瀏覽器使用文件系統,使用cookies,會話存儲或本地存儲。 – awd

+0

那又要做什麼? – ineedanswerz

回答

0

如果您使用的是Chrome瀏覽器,由於跨域安全限制,它將阻止您打開該文件。 Firefox瀏覽器可能適合你。

我的建議是安裝一些本地服務器,如WAMP或XAMP。並嘗試從那裏運行該文件。

相關問題