0
我在javascript中創建HTML DOM,您會看到下面的代碼。現在,我想將我在JavaScript中創建的輸入的值發送到服務器端。我的服務器是用node.js和express框架創建的。將值發送到服務器端後,我想將此值保存在我的json文件中。我知道如何讀取和寫入json文件,但我的問題是發送這個值。這裏是我的javascript代碼和表達代碼。在javascript代碼中,我想發送inTask變量,並且在服務器代碼中我想要在app.post
中收到此值。發送從JavaScript(客戶端)的值來表示(服務器端)
1.javascript代碼
let newTask = [];
function addInput() {
document.getElementById("link").style.display = "none";
var input = document.createElement("input");
input.type = "text";
input.setAttribute("id", "inValue");
document.getElementById("input").appendChild(input);
var addBtn = document.createElement("button");
var text = document.createTextNode("Add Task");
addBtn.appendChild(text);
addBtn.addEventListener("click", addTask);
document.getElementById("input").appendChild(addBtn);
}
function addTask() {
var inTask = document.getElementById("inValue").value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("POST", "/login", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-
urlencoded");
xhttp.send(document.getElementById("inValue").value);
}
- server.js:
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
var fs = require('fs');
app.use(express.static(__dirname + "/static"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended:true }));
app.get("/" , function (req, resp, next) {
resp.sendFile(__dirname + "/static/index.html");
}) ;
app.post("/login" , function (req, resp, next) {
var jsonData = req.body.inValue;
fs.writeFile("data.json", jsonData, function(err) {
if(err) {
return console.log(err);
}
});
res.json(jsonData);
});
app.listen(3000);
console.log("app running on port 3000");
什麼是當前的代碼的問題。你看到的任何錯誤? –
發送空值並且不能識別輸入框的值 – Parisa
您可以爲此使用'ajax'。 –