[英]Do I need an XMLHttpRequest to change a JSON file value with JavaScript?
So I'm trying to make a game where people can change their display name and then store it in a JSON file so that other files and pages can access it.所以我正在尝试制作一个游戏,人们可以更改他们的显示名称,然后将其存储在 JSON 文件中,以便其他文件和页面可以访问它。 So I added an XMLHttpRequest but I then read this article and wondered whether I actually need the XMLHttpRequest.
所以我添加了一个 XMLHttpRequest 但我读了这篇文章,想知道我是否真的需要XMLHttpRequest。 I will attach the JavaScript and JSON files to give a bit more context.
我将附上 JavaScript 和 JSON 文件以提供更多背景信息。
JavaScript: JavaScript:
var console;
let requestURL = 'displayName.json';
let request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
function sendRequest() {
request.send("displayName");
}
document.getElementById('displayName');
if (displayName = "") {
displayName = 'Soldier';
}
JSON: JSON:
displayNameData {
"displayName": ""
}
You need XMLHttpRequest or fetch to make HTTP requests.您需要 XMLHttpRequest 或 fetch 来发出 HTTP 请求。
Since your JSON is at the end of a URL, you need to use one of them to read it.由于您的 JSON 位于 URL 的末尾,因此您需要使用其中一个来阅读它。
The question you link to has nothing, despite the title, to do with JSON.尽管有标题,但您链接到的问题与 JSON 无关。 It is dealing with the manipulation of JavaScript objects .
它正在处理JavaScript 对象的操作。
If you want the JSON file to provide data to your application AND you want the javascript to update it, then you need to submit your request to a server-side handler that then generates the JSON file.如果您希望 JSON 文件向您的应用程序提供数据并且您希望 javascript 更新它,那么您需要将您的请求提交给服务器端处理程序,然后生成 Z0ECD11C1D7A287401D148A23BBD7A2F8 文件。 Currently, your code will just return the static JSON file.
目前,您的代码将只返回 static JSON 文件。
It is not clear what you are trying to do with this code.目前尚不清楚您要使用此代码做什么。
If you want the user's browser to send information to your server, you need an HTTP request .如果您希望用户的浏览器向您的服务器发送信息,您需要一个 HTTP 请求。
For this reason, they are very important to web development and worth your time to learn about.因此,它们对 web 的开发非常重要,值得您花时间学习。
Check out one or both of these resources to dive in:查看这些资源中的一项或两项以深入了解:
Note that communication with the server generally happens asynchronously so the browser can keep working on other things until the server responds.请注意,与服务器的通信通常是异步发生的,因此浏览器可以继续处理其他事情,直到服务器响应。 Therefore, to notice when the server responds, you need to use either
因此,要注意服务器何时响应,您需要使用
Happy coding!快乐编码!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.