【问题标题】:Django POST using AJAX not working使用 AJAX 的 Django POST 不起作用
【发布时间】:2019-01-26 22:11:25
【问题描述】:

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

我有一个 html 页面,我从该页面发送 AJAX XMLHttpRequest POST 到我的 localhost 托管 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 时,它不起作用。

【问题讨论】:

  • 提供的本地端点是什么? Django REST 框架?还是返回application/json 的视图?端点 CSRF 是否豁免?我可能有一个例子,具体取决于 jQuery 中的答案。
  • 端点只是一个处理从 html 页面请求的 url 的视图。 bankckend 是 csrf 豁免的。该视图现在只是返回一个成功字符串,但最终我会在它工作后返回 json。

标签: ajax django python-3.x cors django-cors-headers


【解决方案1】:

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

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

另外,AJAX/jQuery 发布请求更改为:

 $( "#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" );
                        });
                    });

【讨论】:

    猜你喜欢
    • 2016-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-25
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    相关资源
    最近更新 更多