通过AJAX调用

时间:2016-04-11 16:55:52

标签: javascript jquery ajax django

我有以下代码(jQuery)来创建一个json文件:

$( ".save" ).on("click", function(){
var items=[];


$("tr.data").each(function() {

 var item = {
  item.Code : $(this).find('td:nth-child(1) span').html(),
  itemQuantity : $(this).find('td:nth-child(4) span').html()        
 };
items.push(item);       

 });

});

现在这是我的AJAX功能:

(function() {
        $.ajax({
            url : "", 
            type: "POST",
            data:{ //I need my items object, how do I send it to backend server (django)??
                    calltype:'save'},
            dataType: "application/json", // datatype being sent

            success : function(jsondata) {  

                //do something
            },

                error : function() {
                    //do something
                }
        });
    }());

现在,我怀疑的是如何将我创建的'item []'对象发送到后端?我确实需要发送item []对象和变量'calltype'来表示AJAX调用的内容,因为我在后端由不同的AJAX函数调用相同的Django View(它与Django的Controller等价)。

我的AJAX功能如何?

1 个答案:

答案 0 :(得分:1)

嘿,伙计们我的答案是正确的。 我使用以下ajax函数来纠正它:

(function() {
        $.ajax({
            url : "", 
            type: "POST",
            data:{ bill_details: items,
                calltype: 'save',
                'csrfmiddlewaretoken': csrf_token},
            dataType: 'json',               
            // handle a successful response
            success : function(jsondata) {  

                console.log(jsondata); // log the returned json to the console
                alert(jsondata['name']);
            },

                    // handle a non-successful response
                error : function() {
                    console.log("Error"); // provide a bit more info about the error to the console
                }
        });
    }());

所以,这是一种自我回答! :)非常感谢SO !!

相关问题