【问题标题】:Chrome automatically refresh page after XMLHttpRequestXMLHttpRequest后Chrome自动刷新页面
【发布时间】:2018-04-23 12:58:30
【问题描述】:

我在使用 Google Chrome 时遇到了一些奇怪的问题。我为我的网站建立了一个搜索字段。因此我实现了一些 JS 来获取和处理结果(见下文)。问题是,当我第一次使用 chrome 进入页面并使用“Enter-key”进行搜索时,chrome 会执行以下操作(来自我的服务器的请求):

[10/Nov/2017 10:00:56] "GET /app/student/home/ HTTP/1.1" 200 7372 (entering the page)
[10/Nov/2017 10:00:59] "GET /api/searchCourse/daf/ HTTP/1.1" 200 95 (search request)
[10/Nov/2017 10:00:59] "GET /app/student/home/? HTTP/1.1" 200 737 (reloading -but why?? )

一个 Firefox(也带有“Enterkey”)或 Chrome 使用“搜索按钮”看起来不同,就像那样。

[10/Nov/2017 10:00:59] "GET /api/searchCourse/daf/ HTTP/1.1" 200 95 (entering the page)
[10/Nov/2017 10:00:59] "GET /app/student/home/? HTTP/1.1" 200 737 (search request)

我也试过用 Chrome 调试这个问题,但它的行为应该是这样的。另外我必须补充一点,这仅在我登录后首次进入页面时才会发生。当我刷新页面时,它工作得很好。有人可以解释这种行为吗?

我的 JS 代码:

var btnSearch = document.querySelector('.search').addEventListener('click', searchCourse);
var txtFieldSearch = document.getElementById('searchField').addEventListener('keydown',                 
    function (e) {
        var key = e.which || e.keyCode;
        if (key === 13) {
            searchCourse();
        }
    }
);

function searchCourse() {
    document.querySelector('.my-node').style.display = 'none';
    var input = document.getElementById('searchField').value;
    var url = '/api/searchCourse/';

    if (input.length < 3) {
        showSearchWarining('Please enter more than 3 letters.');
        return;
    }

    var xhr = new XMLHttpRequest();
    xhr.open('GET', url + input, true);
    xhr.onload = function (e) {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                console.log(xhr.responseText);
                addResults(xhr.responseText);
            } else {
                console.error(xhr.statusText);
            }
        }
    };
    xhr.onerror = function (e) {
        console.error(xhr.statusText);
    };
    xhr.send(null);
}

【问题讨论】:

  • 看起来 Chrome 在按下回车键时正在提交按钮表单 - 您是否在点击处理程序或表单提交处理程序中尝试了 event.preventDefault()?
  • 你好,对不起。感谢 Joschi,它确实有效。但是你能解释一下 event.preventDefault() 的作用吗?没有得到 Mozilla 的解释。
  • @Joschi,如果您愿意,请将其发布为解决方案,以便我将其标记为解决方案
  • 好的,并为 preventDefault() 添加了指向 mdn 文档的链接。它基本上阻止了事件的默认浏览器行为。
  • 好的,它会阻止默认事件处理,但为什么它不能只在 chrome 上工作?使用 Firefox 运行良好。

标签: javascript html django google-chrome


【解决方案1】:

Chrome 似乎正在提交表单 - 您是否尝试在点击处理程序或表单提交处理程序中使用 event.preventDefault() 以防止调用进一步的事件处理?

【讨论】:

    猜你喜欢
    • 2014-10-18
    • 2011-04-30
    • 2012-07-21
    • 2011-02-13
    • 2019-05-26
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 2013-03-22
    相关资源
    最近更新 更多