【问题标题】:Can't pass array via Ajax to Django view?无法通过 Ajax 将数组传递给 Django 视图?
【发布时间】:2014-11-29 09:38:31
【问题描述】:

我是 ajax 新手,我想将 java 脚本中的数组传递给我的视图。

这是我的模板。我有一个表格,可以从学生那里获取课程 ID 号和课程分数,然后创建表格并添加学生想要添加的课程数量。

我在 javascript 中有一个名为“stock”的变量。 "stock" 存储所有选定课程的 idnumber 和分数。我想发送股票以查看以将所选课程添加到数据库。我使用 Ajax 来做这件事,但它不起作用,因为得到“做某事时出错”。

<!DOCTYPE html>
<html>
<head >

<title>Add new course</title>
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'student/css1.css' %}" /> 
{% include "student/base.html" %}   
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

</head>
<body>
<div id="metric_results">
<div id="form">
   <form name="myForm"   method="post">
        {% csrf_token %}
        {{ form.non_field_errors }}
                <div id="form-data">
                {{ form.course_id }}{{ form.course_id.errors }}
                <label for="id_course_id">ID number:</label><br>

                {{ form.score }}{{ form.score.errors }}
                <label for="id_score">score:</label><br>
                <p id="add_button"><input type="button" value="add"  /></p>
                <p><input type="submit" value="submit" /></p>
                </div>
        </form>
    </div>

    <div id="table">
    <table id="TABLE" border = '1'>


    </table>
    </div>



<script type="text/javascript">
    //when click on "add" button,call "addTable" function.
    document.getElementById("add_button").onclick = function() {addTable()};
    document.getElementById("delete_button").onclick = function() {DeleteTableRow()};

    var stock = new Array();
    var i = 0;

    function addTable() {

        var id = document.forms["myForm"]["course_id"].value;
        var score = document.forms["myForm"]["score"].value;
        var c = document.createElement("INPUT");
        var heading = new Array();
        c.setAttribute("type", "checkbox");
        stock[i] = new Array(id, score);
        //table heading
        heading=["idnumber","score","delete"];
        //check Is there selected course in table
        for(j=0; j<i; j++){if (stock[j][0] == id){alert("this course was selected.");}}


        //Get the table that shows the selected course from html code
        var table = document.getElementById('TABLE');
        //At first create table heading
        if(i==0){
        var tr = document.createElement('TR');
        for(j=0;j<3;j++){
        var th = document.createElement('TH');

        th.appendChild(document.createTextNode(heading[j]));
        tr.appendChild(th);}

        table.appendChild(tr);}

        //Create table row and append it to end of table
        var tr = document.createElement('TR');
        for (j = 0; j < 3; j++) {
                var td = document.createElement('TD');
                if(j == 2){
                    td.setAttribute("id","check_box"+(i+1));
                    td.appendChild(c);}
                else{
                    td.setAttribute("id","rows"+(i+1));
                    td.appendChild(document.createTextNode(stock[i][j]));}
                tr.appendChild(td);
                }

        table.appendChild(tr);
        document.forms["myForm"]["course_id"].value="";
        document.forms["myForm"]["score"].value="";  
        i=i+1;
    }


var postUrl = "http://localhost:8000/student/{{id}}/student_add_course/";
$('form[name="myForm"]').submit(function(){
$.ajax({
url:postUrl,
type: "POST",
data: {'stock': stock},
error:function (xhr, textStatus, thrownError){
    alert("error doing something");
},
})
});
</script>
</body>
</html>

这是我的看法:

def student_add_course(request,student_id):
    if request.method=='GET':
        context={'id':student_id , 'form':AddCourseForStudentForm()}
        request.session['ListOfCourses']=[]
        return render(request, 'student/AddCourseForStudentForm.html',context)
    elif request.method=='POST':
        print request.POST.getlist('stock[]')
        return render(request, 'student/add_course.html')

代码有什么问题?有没有更好的方法来做到这一点?

如果有人帮助我,我会很高兴。

对不起,我的英语不好。

【问题讨论】:

  • 执行alert(thrownError); 以查看错误是什么。
  • 我这样做并说禁止
  • @user3789719 您需要传递 csrf 令牌,因为您正在执行 ajax POST 请求。
  • @mariodev 感谢您的回答。您能解释一下如何传递 crf 令牌吗?

标签: javascript jquery python ajax django


【解决方案1】:

首先尝试为您的视图关闭 csrf 保护:

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def student_add_course(request,student_id):

如果有帮助,请在此处阅读有关在 AJAX 中传递 csrf 的信息: https://docs.djangoproject.com/en/dev/ref/csrf/#ajax

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    相关资源
    最近更新 更多