我是 Javascript 新手,我可以在从表单中点击提交后使用 XMLHttpRequest()
但结果应该与 onclick 事件相同。我有一个名为 get
的函数,通过使用 XMLHttpRequest()
我可以在 div sample
中添加一个新对象,如果它是一个按钮,它就可以工作。唯一的区别是,我想在提交后向 div sample
添加新对象,而不重定向到 http://127.0.0.1:5000/get?query=apple
在这种情况下,表单、表单和函数 get() 应该一起工作。而且我不想在提交表单后在浏览器的 url 字段中看到 http://127.0.0.1:5000/get?query=apple
。我需要一些帮助,我强制自己尽可能使用纯 js,而不是依赖 jquery。
<div id="sample"></div>
<div onclick="get('apple');">CLICK APPLE</div>
<form action="/get" method="GET">
<input name="query">
<input type="submit">
</form>
<script>
function get(query) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("sample").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "get?query=" + query, true);
xhttp.send();
};
</script>
最佳答案
这就是你可以中断提交事件并做任何你想做的事情的方法。
<div id="sample"></div>
<div onclick="get('apple');">CLICK APPLE</div>
<form id="form">
<input name="query">
<input type="submit" value="Submit">
</form>
<script>
document.querySelector('#form').addEventListener('submit', function(e){
e.preventDefault();
var query = e.target.elements['query'].value;
get(query);
});
function get(query) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("sample").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "get?query=" + query, true);
xhttp.send();
};
</script>
关于javascript - 从表单提交后的 XMLHttpRequest(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51007541/