[英]Ajax call to another Node.js server?
I don't have a specific question, but rather, I need something to be explained. 我没有特定的问题,但是我需要解释一些问题。 I'm doing an assignment that requires that I use AJAX (WITHOUT JQuery) to display a list once the page loads.
我正在做一项作业,要求我在页面加载后使用AJAX(WITHOUT JQuery)显示列表。 However, I'm confused about a part of the instructions.
但是,我对其中的一部分说明感到困惑。
"...presented with. Once the page loads, an Ajax call should call to a Node.js server to retrieve the top 10 list . Then the list must be presented to the user as numbered list. The items..." “ ...呈现。页面加载后, Ajax调用应调用Node.js服务器以检索前10个列表 。然后该列表必须以编号列表的形式呈现给用户。项目...”
Does this mean I need to create another Node.js server in addition the one I've already created or can this all be done within one server? 这是否意味着除了已经创建的Node.js服务器之外,我还需要创建另一台Node.js服务器,还是可以在一个服务器中完成所有这些工作? I'm very confused about this part.
我对这部分感到非常困惑。
This is my Node.js server. 这是我的Node.js服务器。
'use strict';
const express = require('express'),
request = require('request'),
app = express();
app.set('view engine', 'pug');
app.set('views', './views');
app.use(express.json());
app.use(express.urlencoded({
extended: true
}));
app.use(express.static('public'));
app.get('/', function (req, res) {
res.render('index');
});
app.listen(3000, function () {
console.log('Listening on http://localhost:3000');
});
This is my PUG template. 这是我的PUG模板。
doctype
html
head
meta(charset="UTF-8")
meta(name="viewport", content="width=device-width, initial-scale=1")
block title
title This is the title!
link(rel='stylesheet', href='/css/style.css', type='text/css')
body
h1 This is a header!
div#banner
p#demo This is a description!
script(src='/js/mrvl_ajax.js')
This is my AJAX call function. 这是我的AJAX调用函数。
'use strict';
window.addEventListener("load", function(event) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
document.getElementById("demo").innerHTML = this.responseText;
};
xhttp.open("GET", "**Server Location?**", true);
xhttp.send();
});
You can create another endpoint on your Node.js server. 您可以在Node.js服务器上创建另一个端点。
app.get('/data', function (req, res) {
res.json({"list": ["item1", "item2"]});
});
then call that endpoint from the client with ajax 然后使用ajax从客户端调用该端点
xhttp.open("GET", "/data", true);
the data returned will be the JSON data {"list":["item1", "item2"]}
, which you can then use javascript to order it how you need to. 返回的数据将是JSON数据
{"list":["item1", "item2"]}
,然后可以使用javascript对其进行排序。
also, inside your onreadystatechange
function you will want this if statement to make sure the call completed successfully before you grab the responseText from the response 此外,在
onreadystatechange
函数中,您将需要此if语句来确保在从响应中获取responseText之前,调用已成功完成
xhttp.onreadystatechange = function() {
if (xhttp.readyState === 4 && xhttp.status === 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.