使用AJAX的Django POST不起作用



我有一个 django 后端,我在其中添加了 corsheader 和中间件。

我有一个 html 页面,我从中将 AJAX XMLHttpRequest POST 发送到我的本地主机托管 django 应用程序,但帖子从未通过。它触发一个GET事务,并且该事务永远不会到达服务器。

前端HTML页面的代码如下:-

<button type="submit" class="btn btn-success btn-lg" id="sub1" 
onClick=loadDoc() >Login </button>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if( this.readyState == 4 && this.status == 200 ) {
location.replace(Trial.html);
}
};
xhttp.open("POST", "http://localhost:XXXX/XXXX/XXXX/", true)
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();
}
</script>

谁能指出哪里出了问题?当我使用表单数据时,帖子有效,但当我使用 javascript 时它不起作用。

发生这种情况的原因是 CORS。

现代浏览器不支持跨源请求。所以,我不得不下载并安装Django CORS头模块。相应地更新设置文件,以允许来自其他源的请求通过。

此外,AJAX/jQuery post 请求已更改为:

$( "#loginForm" ).submit(function( event ) {
// Stop form from submitting normally
event.preventDefault();
var jqxhr = $.post( "http://XXXX.com/xxxx/xxxx/", $( "#loginForm" ).serialize(), function() {
alert( "success" );
})
.done(function( data ) {
if( data == "SUCCESS") {
location.replace("xxxx.html");
}
else {
alert("WRONG CREDS");
}
})
.fail(function() {
alert( "error" );
});
});

最新更新