Django POST 使用 AJAX 不工作

Django POST using AJAX not working

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

我有一个 html 页面,我从该页面发送 AJAX XMLHttpRequest POST 到我的本地主机托管 django 应用程序,但 post 从未通过。它触发一个 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>

谁能指出哪里不对?当我使用表单数据时 post 有效,但当我使用 javascript.

时它不起作用

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

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

此外,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" );
                        });
                    });