我是js的新手,所以對我來說很簡單。 我的主要目標是從Message.js(一個名爲消息的數組)中獲取參數並在服務器中使用它們。 這部分只需在屏幕上打印即可。如何從node.js服務器中的.js獲取和使用變量和參數?
tnx給幫手! :)
我Message.js文件看起來像這樣:
$(document).ready(function() {
var messages = [
{
name: 'I am Message number one', //a js field in an object(message in this case) and it's value after the semicolon
texts: [ //an array of 3 strings in js
'mary had a little lamb',
'hail hydra',
'spider-man rocks'
],
images: [ //an array of 2 images in js
'https://fb-s-c-a.akamaihd.net/h-ak-xat1/v/t1.0-9/10156120_630371003705480_8529510393733631385_n.png?oh=8412d9c3b69d39b6030d66f9709e1e1e&oe=58EEA4F2&__gda__=1492580526_84a87f898177ec43770cf3a5317fdb31',
'https://fb-s-a-a.akamaihd.net/h-ak-xtf1/v/t1.0-9/10268685_630867936989120_785222708436272994_n.jpg?oh=c15c538b5385843ad0b44affda0f378c&oe=58B9EB5F&__gda__=1488430186_6c7c227a21e77492f092dc999834157d'
],
times: [ //array of vars initialized in Dates kind values
{
fromDate: new Date(2016, 0, 1), //jan is 0, feb is 1, and so on...
toDate: new Date(2016, 11, 31),
fromTime: '09:00',
toTime: '22:53',
days: [0, 1, 5] // sunday starts with a 0 then monday is 1 and so on...
}
]
}, //until here this is a one object of 'message'
{
name: 'I am Message number two', //a js field in an object(message in this case) and it's value after the semicolon
texts: [
'soon in theaters', //an array of 4 strings in js
'the lion king is Simba',
'tiom&pumba rules',
'spider-man is awesome!'
]
}];
}
,我不知道該怎麼做服務器的部分 試過這樣的事情:
var http = require('http');
var port = 8080;
var fs = require("fs");
const querystring = require("querystring");
function onRequest(request, response){
console.log("user made a request " + request.url);
response.writeHead(200);
response.write(messages[0].name);
response.write("here is your data");
response.toString(message[0]);
response.end();
}
http.createServer(onRequest).listen(port);
你只談論服務器端,或者你想從客戶端發送此數組服務器? – 2016-12-27 17:33:16
Did [my answer](https://stackoverflow.com/questions/41349459/how-to-get-and-use-variables-and-parameters-from-js-in-node-js-server/41349513#41349513 )下面回答你的問題?任何意見? – rsp
客戶端到服務器。主要目標是顯示一個網站,顯示幾條消息,而不需要重新加載,所以對於這個邏輯我使用setInterval() 來顯示消息從一個HTML文件,呈現和顯示這些消息。現在我正在嘗試擴展該項目,並使用服務器從.js文件獲取數據,並將其發送給客戶端進行渲染並顯示。 –