无法通过Ajax将数组传递到Django视图?

时间:2014-11-29 09:38:32

标签: javascript jquery python ajax django

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

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

我在javascript中有一个名为“stock”的变量。 “stock”存储所有选定课程的编号和分数。我想发送库存以查看将所选课程添加到数据库。我使用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')

代码有什么问题?有没有更好的方法呢?

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

我很抱歉我的英语不好。

1 个答案:

答案 0 :(得分:0)

首先尝试关闭视图的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