javascript - 从表单提交后的 XMLHttpRequest()

标签 javascript html

我是 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/

相关文章:

java - HTML5 本地存储离线缓存在 Google AppEngine 应用程序中不起作用

javascript - 如何禁用手机上出现的键盘 : React date time picker

javascript - 检测键盘中的左侧或右侧 Shift 键 - JavaScript

html - CSS 关键帧 - 缩放和平移

javascript - 如何使用 javascript 更新 HTML 内容但使用 PHP 获取内容

html - 正文背景图片未显示

javascript - 关闭 jQuery 对话框

javascript - 使用 JQuery 将 JSON 数组数据的选择打印到页面

javascript - 根据选项标签创建不同的表单

css - 尝试仅使用 div 和 css 而不是表格来实现格式化