【发布时间】:2019-07-28 13:23:23
【问题描述】:
我正在练习没有任何框架(如 jquery、expressJS)的 node js 和 ajax,方法是做一个使用 openweatherapi 提供有关城市天气信息的简单应用程序。 到目前为止,这是我的代码: app.js
const http = require("http");
const fs = require("fs");
const path = require("path");
const { parse } = require('querystring');
const server = http.createServer((req, res)=>{
if(req.url === "/"){
fs.readFile("index.html", "UTF-8", function(err, data){
res.writeHead(200, {"Content-Type": "text/html"});
res.end(data);
});
}else if(req.url === "/public/styles.css"){
var cssPath = path.join(__dirname + req.url);
var cssFileStream = fs.createReadStream(cssPath, "UTF-8");
res.writeHead(200, {"Content-Type": "text/css"});
cssFileStream.pipe(res);
}else if(req.url === "/public/main.js"){
var jsFileStream = fs.createReadStream(`${__dirname}/${req.url}`, "UTF-8");
res.writeHead(200, {"Content-Type": "text/js"});
jsFileStream.pipe(res);
}else if(req.url === "/favicon.ico"){
res.statusCode=204;
res.end();
};
if(req.url ==="/"&&req.method==="POST"){
let body = "";
req.on('data', chunk=>{
body += chunk.toString();
});
req.on("end", ()=>{
parse(body);
});
console.log(body);
};
});
var PORT = process.env.port || 3000;
server.listen(PORT);
console.log(`Server listening on port ${PORT}`);
index.html
<!DOCTYPE html>
<html>
<head>
<title>Weather Application</title>
<link href="./public/styles.css" rel="stylesheet" type="text/css"/>
<script src="./public/main.js"></script>
</head>
<body>
<div class="weather-div">
<h1> Search for weather information of a city</h1>
<form method="post" action="/">
<input class="locationName" id="cityName" name="city" type="text" placeholder="City" required/>
<input class="locationName" id="countryName" name="city" type="text" placeholder="Country"/>
</form>
<button id="submitBtn" type="submit">Search Weather</button>
</div>
<body>
</html>
main.js
function getData(){
var city = document.getElementById('cityName');
var country = document.getElementById('countryName');
if(city.value.length>0){
const apiKey = "APIKey";
const apiUrl = "http://api.openweathermap.org";
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
};
};
xhttp.open("POST", "app.js",true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(`city=${city}&country=${country}`);
};
};
window.onload=function(){
document.getElementById("submitBtn").addEventListener("click", getData, false);
};
所以我想做的是使用 ajax 发送输入的城市名称,因为我尝试使用简单的表单和提交按钮,但它会不断刷新页面。我不想要它。我希望在 app.js 中接收数据以解析它并使用城市的 json 文件过滤其代码,然后将其返回给 main.js 以向 openweathermap 发送 api 调用。 幸运的是,我知道如何做一些简单的事情:解析和 api 调用。但所有其他的东西我完全不知道。当我搜索它时,我只找到使用 jquery 或 express 的解决方案,但我不希望这样,我希望纯 javascript 变得更好。 先感谢您。
【问题讨论】:
标签: javascript html node.js ajax