通过AJAX将数据保存到服务器无法正常工作

时间:2015-12-10 13:53:48

标签: javascript jquery json ajax knockout.js

在淘汰赛中我的保存功能有些问题。我正在关注Knockout网站http://jsfiddle.net/rniemeyer/bGsRH/上的教程。当我将代码实现到我的网站时,我收到错误400错误请求声明我的JSON数据无效。调试了一下后,我发现它返回[object,object]而不是我修改过的JSON数据。

为了给出一些上下文,我基本上有一个包含我的数据列表的表,每行都有他们的编辑按钮。单击编辑按钮后,它将打开一个模态并显示所选项目的数据。当我尝试修改然后保存数据时会出现问题。

这是我到目前为止的javascript代码,有人知道我缺少什么吗?:

<script type="text/javascript">
function EmployeeModal() {
     var self = this;
     self.Employees = ko.observableArray([]);

    //Start of select/edit functions
    //This codes allows to pass selected data to the hidden modal
     self.currentEmployee = ko.observable(null);
     self.showEmployee = function(vm){
         self.currentEmployee(vm);
         $('#myModal').modal('show');
     };
     //END of select/edit functions
     //Start of the save function
     self.save = function() {
        var New_Incident_URL = '../../../../_vti_bin/listData.svc/GDI_PROD_Incidents';
        var UPDATE_Incident_URL = '../../../../_vti_bin/listData.svc/GDI_PROD_Incidents('+ encodeURIComponent($('#Incident_ID').val())+')';
        var createIncidentUrl = $('#Incident_ID').val() != '' ? UPDATE_Incident_URL : New_Incident_URL;

        var CREATE_Headers = {"accept": "application/json;odata=verbose"};
        var UPDATE_Headers = {"accept" : "application/json;odata=verbose","X-HTTP-Method":"MERGE","If-Match":"*"};
        var headertype = $('#Incident_ID').val() != '' ? UPDATE_Headers : CREATE_Headers;   

        $.ajax(createIncidentUrl, {
            data: {
                json: ko.toJSON({

                        Description: this.Description,

                        Incident: this.Incident

                })
            },
            type: "POST",
            processData: false,
            contentType: "application/json;odata=verbose",
            headers: headertype,
            success: function(result) {
                alert(ko.toJSON(result));
                $('#myModal').modal('hide');
            }
        });
     };


     //Start - Go get data from Sharepoint.
    $.getJSON("../../../../_vti_bin/listData.svc/GDI_PROD_Incidents?$filter=ÉtatValue%20ne%20%27Fermé%27&$orderby=PrioritéValue desc",
        function (data) {
        if (data.d.results) {
            self.Employees(ko.toJS(data.d.results));
            }
        }
    );  
    //END - Go get data from Sharepoint.

}
     $(document).ready(function () {
         ko.applyBindings(new EmployeeModal());
     });

</script>

编辑: 以下是来自服务器的数据示例。

   [{
        ID: "123",
        Description: "The server x is unavailable",
        Incident: "1234"
    }, {
        ID: "124",
        Description: "The router located downtown is down",
        Incident: "12345"
    }, {
        ID: "125",
        Description: "Fiber optic cable downtown is flapping",
        Incident: "123456"
    }, {
        ID: "126",
        Description: "Network unvailable at the beaver site",
        Incident: "1234567",
    }];

0 个答案:

没有答案