我有一个像这样的简单 HTML 表单:
<div class="border-little text-center grey">
<form action="https://www.THIS IS MY URL.php" method="get">
<input name="player" id="player" value="1" class="hidden">
<label for="number">Enter a number</label>
<input type="text" id="number" name="number" placeholder="">
<input type="submit" value="Submit">
</form>
</div>
操作如下: 玩家输入一个数字,服务器使用 JSON 格式回答。
我的问题: 当我按下“提交”时,我的网页离开并重定向到服务器页面,显示 JSON 格式的答案。
我想做什么: 我想留在我的页面上并能够接收 JSON 格式的答案并将它们显示在我的表单下方,而不是被重定向到服务器页面。
更多详情: 我从服务器获得的 JSON 答案示例:
{"guess": "lower"}
我不能使用任何类型的 JavaScript 库,因此禁止使用 JQuery。
最佳答案
你用js的ajax方法就可以了
function r_submit() {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "https://www.THIS IS MY URL.php", true);
var params = {"player":document.getElementById("player").value};
xhttp.send(params);
xhttp.onload = function() {
alert(xhttp.responseText);
}
}
点击按钮时执行r_submit()函数按钮
这里你的 html 代码会是这样的
<div class="border-little text-center grey">
<input name="player" id="player" value="1" class="hidden">
<label for="number">Enter a number</label>
<input type="text" id="number" name="number" placeholder="">
<input type="submit" value="Submit" onsubmit='r_submit()'>
</form>
</div>
关于javascript - 提交表单并在没有 jQuery 的情况下获得 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50895909/