【问题标题】:How to use Ajax in Django如何在 Django 中使用 Ajax
【发布时间】:2019-01-04 09:49:06
【问题描述】:

我在这里需要一些帮助,我正在尝试做一个简单的 POST 来传输数据以在 django 中查看,但我收到了一个错误,模板包含一个简单的输入,当我们点击时,POST 过程开始 这是我的模板:

{% block javascript %}
    <script src="{% static 'js/test.js' %}"></script>
{% endblock javascript %}

{% block content %}
  <form method="post" enctype="multipart/form-data">

      {% csrf_token %}

  <center>
     <div class="submit-buttons">
         <input type="submit" value= "add" id="add_button" onclick="post_metadata()" />
     </div>
  </center>

 </form>-
{% endblock content %}

这是 JS 块:

function getCookie(c_name){
    if (document.cookie.length > 0){
    c_start = document.cookie.indexOf(c_name + "=");

       if (c_start != -1){
         c_start = c_start + c_name.length + 1;
         c_end = document.cookie.indexOf(";", c_start);

         if (c_end == -1) c_end = document.cookie.length;
             return unescape(document.cookie.substring(c_start,c_end));
    }
}
return "";
 }


var post_metadata = function (){
        $.ajaxSetup({
            headers : {  "X-CSRFToken": getCookie("csrftoken")  }
        });
        $.ajax({
                url         : "add/",
                type        : 'POST',
                dataType    : 'json',
                data        : { '1':"ash", '2':"raph" },
                cache       : false,

                success: function(){
                    console.log("It's all right")
                },

                error: function handleFormError(jqXHR, textStatus, errorThrown){
                     console.log(jqXHR)
                     console.log(textStatus)
                     console.log(errorThrown)

    },
            }); // ajax
         };

并查看文件:

@csrf_protect
def add_actors_in_pool(request):
    print(">>>>>>>>>>>>>>>>> add actor <<<<<<<<<<<< ")
    print (request.POST["1"])
    print (request.POST["2"])

    return render(request, "packages/dashboard.html")


def main_view(request):
    print("<<<<<<<<<<<<<< main >>>>>>>>>>>>>>>>>>")

    return render(request, "test1.html")

最后是控制台和错误: console and error

【问题讨论】:

  • 请将您的问题更新为文本形式的实际代码,而不是图像。 Why not upload images of code on SO when asking a question?
  • @MadhanM 对不起,我试图用不同的方式来做,我忘了改变它
  • 好像你得到 4XX 错误。您在 django 的日志中收到的状态消息是什么?
  • @MadhanM 状态为 304 ,我的主要问题是,在单击后它应该将我重定向到 packages/dashboard.html 但它没有,谢谢您的回复。
  • Ajax 不会重定向页面。您从帖子中获得的是来自 POST 响应数据对象内新页面的 html 代码。请check this

标签: javascript ajax django post


【解决方案1】:

好的,谢谢@AchrafElAlaoui。似乎您正在返回 html 作为对成功帖子的响应,但您已指定您期望 json 作为响应。应该是dataType:"html"please check here 了解更多详情。您的提交函数应该看起来像这样。

var post_metadata = function (event){
event.preventDefault(); // to prevent page from reloading
    $.ajaxSetup({
        headers : {  "X-CSRFToken": getCookie("csrftoken")  }
    });
    $.ajax({
            url         : "add/",
            type        : 'POST',
            dataType: "html",  // Since you're returning html as response
            data        : { '1':"ash", '2':"raph" },
            cache       : false,

            success: function(){
                alert("It's all right");
                //window.location = "/dashboard"; // If you want to redirect on successful post.
            },

            error: function handleFormError(jqXHR, textStatus, errorThrown){
                 console.log(jqXHR)
                 console.log(textStatus)
                 console.log(errorThrown)

},
        }); // ajax
     }; 

【讨论】:

  • 我把它变成了 html 但没有任何改变
  • @ASH 你的问题解决了吗?
  • 我不知道链接指的是什么,但它给了我一个错误“无法完成隧道连接”,PS:我的服务器正在8000上工作
  • 你能再试一次吗?
  • 好的,非常感谢。
猜你喜欢
  • 2020-01-16
  • 2014-02-17
  • 2015-12-22
  • 2012-11-08
  • 2012-03-09
  • 2011-07-04
  • 1970-01-01
  • 2021-12-27
  • 2012-03-28
相关资源
最近更新 更多