以下是代碼:我正在寫一個函數來更新json
文件中的顏色屬性。我能夠更新對象,但無法將其寫回文件(修改文件)。當用戶通過表單輸入時,我需要更新json
數據文件。我想更新.json文件,請告訴我怎麼去
function updatecolor(id, color) {
$.ajax({
type: "GET",
dataType: "json",
url: "Data.json",
cache: false,
beforeSend: function() {
$('#table').html('loading please wait...');
},
success: function(jsondata) {
console.log(jsondata);
count = jsondata.length;
for (i = 0; i < jsondata.length; i++) {
if (jsondata[i].id == id)
jsondata[i].color = color;
}
window.alert(JSON.stringify(jsondata));
}
});
}
function popupform() {
$('#formpop').show();
}
function my() {
$.ajax({
type: "GET",
dataType: "json",
url: "Data.json",
cache: false,
beforeSend: function() {
$('#table').html('loading please wait...');
},
success: function(jsondata) {
console.log(jsondata);
count = jsondata.length;
var str = '';
var str2 = '';
var str3 = '';
//str += '<ul>';
$.each(jsondata, function(idx, obj) {
var match = obj.Color;
if (match == "Blue") {
str += 'ID :' + obj.id + ' Color : ' + obj.Color + '<br> ';
}
});
$.each(jsondata, function(idx, obj) {
var match = obj.Color;
if (match == "Red") {
str2 += 'ID :' + obj.id + ' Color : ' + obj.Color + '<br> ';
}
});
$.each(jsondata, function(idx, obj) {
var match = obj.Color;
if (match == "Green") {
str3 += 'ID :' + obj.id + ' Color : ' + obj.Color + '<br> ';
}
});
//str += '</ul>';
$('#abc').html(str);
$('#abc2').html(str2);
$('#abc3').html(str3);
}
});
}
編輯 - 從註釋部分添加在這裏的服務器代碼:
var http = require("http");
var fs = require("fs");
function send404Response(response){
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("Error 404 - Page not found");
response.end();
}
function onRequest(request, response) {
if(request.method == 'GET' && request.url == '/'){
response.writeHead(200, {"Content-Type": "text/html"}); //Open file as readable stream, pipe stream to response object
fs.createReadStream("./index.html").pipe(response);
}else{
send404Response(response);
}
}
http.createServer(onRequest).listen(8888);
您好請分享更多的代碼 –
您分享的代碼是用於瀏覽器的。服務器上的代碼是什麼? –
var http = require(「http」); var fs = require(「fs」); function send404Response(response){ response.writeHead(404,{「Content-Type」:「text/plain」}); response.write(「Error 404 - Page not found」); response.end(); (request.method =='GET'&& request.url =='/'){ response.writeHead(200,{「Content-Type」:「text/HTML「}); //打開文件作爲可讀流,管道流傳遞給響應對象 fs.createReadStream(「./ index.html」)。pipe(response); } else {send404Response(response); } } http.createServer(onRequest).listen(8888); –