向其他URL发出AJAX GET请求后,从中进行调用的原始URL也会附加GET查询。
使用以下代码,成功向 url 发出了 data='a' 的 AJAX 请求
localhost:8000/ajax/search?query=a
下面是我的 AJAX 请求代码:
$.ajax({
type: "GET",
url: "/ajax/search",
data: {query: data},
dataType: "json",
success: function (a) {
console.log(a);
}
});
但是,在成功收到 JsonResponse 后(我已经确认(,发出 AJAX 请求的原始页面的 URL 会附加 GET 数据。如何防止将 get 请求附加到原始 URL?
以下是来自 Django 服务器的日志数据:
"GET /username/ HTTP/1.1" 200 2947
"GET /ajax/search?query=a HTTP/1.1" 200 96
"GET /username/?query=a HTTP/1.1" 200 2947
我希望 AJAX 响应后的 URL 是/用户名/
单击页面中的某些按钮时有一些功能。在这种情况下, event.preventDefault((;
$("#form").submit(function(event) {
event.preventDefault(); <------
$.ajax({
type: "GET",
url: "/ajax/search",
data: {query: data},
dataType: "json",
success: function (a) {
console.log(a);
}
});
}(;
您可以使用此 Jquery 脚本从 url 中删除任何查询参数
$(document).ready(function(){
if (window.location.href.indexOf('?') > -1) {
history.pushState('', document.title, window.location.pathname);
}
});
使用 window.history.pushState
https://developer.mozilla.org/en-US/docs/Web/API/History_API#Example_of_pushState((_method
$.ajax({
type: "GET",
url: "/ajax/search",
data: {query: data},
dataType: "json",
success: function (a) {
console.log(a);
if (window.location.href.indexOf('?') > -1) { # removes the params in URL if exists
window.history.pushState({}, document.title, window.location.pathname); # this is the magic
}
}
});