我是一名刚入门的客户端新手,需要澄清 Ajax 概念。
e.preventDefault();
是JS中典型的防止表单提交(页面刷新)的方法。
上面的一个用例是基于 Ajax 的表单提交。示例代码是:
function overwrite_default_submit(e) {
// block the default behavior
e.preventDefault();
// create and populate the form with data
var form_data = new FormData();
form_data.append("reply", text_field.value);
// send the form via AJAX
var xhr = new XMLHttpRequest();
xhr.open('POST', e.target.action);
xhr.setRequestHeader("X-CSRFToken", get_cookie('csrftoken'));
xhr.send(form_data);
}
我有两个问题:
1) 假设 POST
请求被发送到一个以 redirect
结尾的函数到不同的 URL。例如,我使用 Django 开发 Web 应用程序;典型的 Django View 可能以 return redirect("home")
结尾,其中 home 是所述应用程序的主页。在这种情况下,preventDefault()
是如何阻止服务器端代码中的redirect
语句执行的呢?我试图了解其背后的确切机制。
2) 如果在 Ajax POST 请求后希望页面刷新(或重定向)正常进行怎么办?需要进行哪些调整?很想看到一个说明性的例子来阐明我的概念。
我精通 Django (Python),所以如果您需要显示服务器端代码,Django 就是一个很好的例子。
注意:因为我最近在学习 JS,所以更喜欢坚持使用纯 JS。 JQuery 在我的雷达上,但只有在我掌握了 JS 的基础知识之后。
最佳答案
preventDefault()
取消事件,元素事件不会发生的默认 Action 。这将简单地停止在该语句之后进一步执行 javascript 代码。
例如
- 点击 submit
按钮,阻止它提交表单。
- 点击一个链接
,阻止链接
跟随给定的
网址
重定向到下一页或添加通知也可能是通过javascript添加html,但这里只是重定向。
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) //Here we need to check OK response and last state of ajax call.
{
window.location.href = 'REDIRECT_URL'
window.location.reload() // To refresh page.
}
};
=== 我已经在你的函数中添加了 ===
function overwrite_default_submit(e)
{
// block the default behavior
e.preventDefault();
// create and populate the form with data
var form_data = new FormData();
form_data.append("reply", text_field.value);
// send the form via AJAX
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) //Here we need to check OK response and last state of ajax call.
{
window.location.href = 'REDIRECT_URL'
window.location.reload() // To refresh page.
}
};
xhr.open('POST', e.target.action);
xhr.setRequestHeader("X-CSRFToken", get_cookie('csrftoken'));
//xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(form_data);
}
现在,对于 Django,您还需要添加 View /调用应返回 json 或 xml 的正确操作。
from django.http import JsonResponse
def some_view(request):
return JsonResponse({"key": "value"})
要了解 ajax 的工作原理,您可以在此处查看 https://www.w3schools.com/xml/ajax_intro.asp
关于javascript - 如何在 Ajax POST 提交后允许页面刷新/重定向(Django 形式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48580837/