我有以下代码(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调用的原因,因为在后端,我有相同的Django View(与Django的Controller等效),由不同的AJAX函数调用。

我的AJAX函数将如何显示?

最佳答案

大家好,我的答案正确了。
我使用以下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
                }
        });
    }());


所以,这是一个自我答案!!! :)非常感谢!

07-24 18:07
查看更多