SAPUI5 (39) - 直接提交 HTTP 请求实现 CRUD

OpenUI5 作为一种客户端的 UI 技术,自身并不直接与后端的服务器或者数据库交互。客户端只是提交 HTTP request,不管是 ODatacreate / update / delete 等方法,还是单向绑定或双向绑定时的 submitChanges 方法,都是对 HTTP Request 的一种封装。网络上有文章介绍 OpenUI5 中如何提交 HTTP request,或者使用 Ajax call 提交 HTTP request。这些方法对于服务器不提供 OData service 的场合有其实用价值。

本文介绍如何在 OpenUI5 中向后端提交 HTTP Request,实现 CRUD 的方法。代码基于第 38 篇的代码进行修改。

基本上,View 的部分没有变化,主要变化集中在 Controller (App.controller.js 文件)中。

Edit


editEmployee: function() {
    var oView = this.getView();
    
    var oChangedData = {
        EmpId: oView.byId("EmpId").getValue(),
        EmpName: oView.byId("EmpName").getValue(),
        EmpAddr: oView.byId("EmpAddr").getValue()
    };

    OData.request({
            requestUri: sServiceUrl + sCurrentPath.substr(1),
            method: "GET",
            headers: {
                "X-Requested-With": "XMLHttpRequest",
                "Content-Type": "application/atom+xml",
                "DataServiceVersion": "2.0",
                "X-CSRF-Token": "Fetch"
            }
        },

        function(data, response) {
            var oHeaders = {
                "x-csrf-token": response.headers["x-csrf-token"],
                "Accept": "application/json"
            };

            OData.request({
                    requestUri: sServiceUrl + sCurrentPath.substr(1),
                    method: "PUT",
                    headers: oHeaders,
                    data: oChangedData
                },
                // success
                function(oData, oRequest) {
                    sap.m.MessageToast.show("Employee updated Successfully");
                    oEmployeeModel.refresh(true);
                },
                // error
                function(oError) {
                    sap.m.MessageToast.show("Employee update Failed");
                });
        },

        function(err) {
            var request = err.request;
            var response = err.response;
            sap.m.MessageToast.show("Error in Get -- Request " + request + " Response " + response);
        });
}

代码说明:

  • 使用 oChangedData 对象表示修改过的数据,一共三个字段。

  • OData.request() 方法提交 HTTP 请求。这里比较 magical 的一点事情,就是 OData model 定义后,就存在全局 (global) 的 OData 对象。

  • serviceUrlonInit 事件中,从 manifest.json 文件获得:

onInit: function() {
    ...

    // get service url from manifest.json
    var config = this.getOwnerComponent().getManifest();
    sServiceUrl = config["sap.app"].dataSources.mainService.uri;

    ...
}

Create

createEmployee: function() {
    var oView = this.getView();

    var oNewEntry = {
        EmpId: oView.byId("EmpId").getValue(),
        EmpName: oView.byId("EmpName").getValue(),
        EmpAddr: oView.byId("EmpAddr").getValue()
    };

    OData.request({
            requestUri: sServiceUrl + "EmployeeCollection",
            method: "GET",
            headers: {
                "X-Requested-With": "XMLHttpRequest",
                "Content-Type": "application/atom+xml",
                "DataServiceVersion": "2.0",
                "X-CSRF-Token": "Fetch"
            }
        },

        function(data, response) {
            var oHeaders = {
                "x-csrf-token": response.headers["x-csrf-token"],
                "Accept": "application/json"
            };

            OData.request({
                    requestUri: sServiceUrl + "EmployeeCollection",
                    method: "POST",
                    headers: oHeaders,
                    data: oNewEntry
                },
                // success
                function(oData, oRequest) {
                    sap.m.MessageToast.show("Employee Created Successfully");
                    oEmployeeModel.refresh(true);
                },
                // error
                function(oError) {
                    sap.m.MessageToast.show("Employee Creation Failed");
                });
        },

        function(err) {
            var request = err.request;
            var response = err.response;
            sap.m.MessageToast.show("Error in Get -- Request " + request + " Response " + response);
        });
}

Delete

deleteEmployee: function() {
    var oView = this.getView();
    var oEntry = {
        EmpId: oView.byId("EmpId").getValue()
    };

    OData.request({
            requestUri: sServiceUrl + sCurrentPath.substr(1),
            method: "GET",
            headers: {
                "X-Requested-With": "XMLHttpRequest",
                "Content-Type": "application/atom+xml",
                "DataServiceVersion": "2.0",
                "X-CSRF-Token": "Fetch"
            }
        },

        function(data, response) {
            var oHeaders = {
                "x-csrf-token": response.headers["x-csrf-token"],
                "Accept": "application/json"
            };

            OData.request({
                    requestUri: sServiceUrl + sCurrentPath.substr(1),
                    method: "DELETE",
                    headers: oHeaders,
                    data: oEntry
                },
                // success
                function(oData, oRequest) {
                    sap.m.MessageToast.show("Employee deleted Successfully");
                    window.location.reload(true);
                },
                // error
                function(oError) {
                    sap.m.MessageToast.show("Employee deletion Failed");
                });
        },

        function(err) {
            var request = err.request;
            var response = err.response;
            sap.m.MessageToast.show("Error in Get -- Request " + request + " Response " + response);
        });
}

Controller 完整代码

以下是 Controller 的完整代码。

sap.ui.define([
    "sap/ui/core/mvc/Controller"
], function(Controller) {
    "use strict";

    var oEmployeeDialog;
    var oEmployeeModel;
    var sServiceUrl;
    var sCurrentPath;
    var sCurrentEmp; // cureent employee

    return Controller.extend("zui5_odata_http_request.controller.App", {

        onInit: function() {
            oEmployeeModel = this.getOwnerComponent().getModel();

            // get service url from manifest.json
            var config = this.getOwnerComponent().getManifest();
            sServiceUrl = config["sap.app"].dataSources.mainService.uri;

            oEmployeeModel.setUseBatch(false);
            this.getView().setModel(oEmployeeModel);

            oEmployeeDialog = this.buildDialog();
        },

        // Build employee dialog
        buildDialog: function() {
            var oView = this.getView();
            var oEmpDialog = oView.byId("employeeDialog");
            if (!oEmpDialog) {
                oEmpDialog = sap.ui.xmlfragment(oView.getId(),
                    "zui5_odata_http_request.view.EmployeeDialog");

                oView.addDependent(oEmpDialog);

                var oCancelButton = oView.byId("CancelButton");
                oCancelButton.attachPress(function() {
                    oEmpDialog.close();
                });
            }

            return oEmpDialog;
        },

        onCreate: function() {
            var that = this;

            var oView = this.getView();
            oEmployeeDialog.open();

            // set form properties
            oEmployeeDialog.setTitle("Create Employee");
            oView.byId("EmpId").setEditable(true);
            oView.byId("SaveEdit").setVisible(false);
            oView.byId("SaveCreate").setVisible(true);

            // clear values of controls
            oView.byId("EmpId").setValue("");
            oView.byId("EmpName").setValue("");
            oView.byId("EmpAddr").setValue("");

            oView.byId("SaveCreate").attachPress(function() {
                // commit creation
                that.createEmployee();

                // close dialog
                if (oEmployeeDialog) {
                    oEmployeeDialog.close();
                }
            });
        },

        onEdit: function() {
            var that = this;
            var oView = this.getView();

            // Set binding
            if (sCurrentPath) {
                oEmployeeDialog.bindElement(sCurrentPath);
            } else {
                sap.m.MessageToast.show("No employee was selected.");
                return;
            }
            oEmployeeDialog.open();

            oEmployeeDialog.setTitle("Edit Employee");
            oView.byId("EmpId").setEditable(false);
            oView.byId("SaveEdit").setVisible(true);
            oView.byId("SaveCreate").setVisible(false);

            oView.byId("SaveEdit").attachPress(function() {
                that.editEmployee();

                // close dialog
                if (oEmployeeDialog) {
                    oEmployeeDialog.close();
                }
            });
        },

        onDelete: function() {
            var that = this;

            if (!sCurrentPath) {
                sap.m.MessageToast.show("Now employee was selected.");
                return;
            }

            // Build dialog
            var oDeleteDialog = new sap.m.Dialog();
            oDeleteDialog.setTitle("Delete Employee");
            oDeleteDialog.addContent(
                new sap.m.Label({
                    text: "Are you sure to delete Employee " + sCurrentEmp + "?"
                })
            );

            oDeleteDialog.addButton(
                new sap.m.Button({
                    text: "Confirm",
                    press: function() {
                        that.deleteEmployee();
                        oDeleteDialog.close();
                    }
                })
            );

            oDeleteDialog.open();
        },

        createEmployee: function() {
            var oView = this.getView();

            var oNewEntry = {
                EmpId: oView.byId("EmpId").getValue(),
                EmpName: oView.byId("EmpName").getValue(),
                EmpAddr: oView.byId("EmpAddr").getValue()
            };

            OData.request({
                    requestUri: sServiceUrl + "EmployeeCollection",
                    method: "GET",
                    headers: {
                        "X-Requested-With": "XMLHttpRequest",
                        "Content-Type": "application/atom+xml",
                        "DataServiceVersion": "2.0",
                        "X-CSRF-Token": "Fetch"
                    }
                },

                function(data, response) {
                    var oHeaders = {
                        "x-csrf-token": response.headers["x-csrf-token"],
                        "Accept": "application/json"
                    };

                    OData.request({
                            requestUri: sServiceUrl + "EmployeeCollection",
                            method: "POST",
                            headers: oHeaders,
                            data: oNewEntry
                        },
                        // success
                        function(oData, oRequest) {
                            sap.m.MessageToast.show("Employee Created Successfully");
                            oEmployeeModel.refresh(true);
                        },
                        // error
                        function(oError) {
                            sap.m.MessageToast.show("Employee Creation Failed");
                        });
                },

                function(err) {
                    var request = err.request;
                    var response = err.response;
                    sap.m.MessageToast.show("Error in Get -- Request " + request + " Response " + response);
                });
        },

        editEmployee: function() {
            var oView = this.getView();
            
            var oChangedData = {
                EmpId: oView.byId("EmpId").getValue(),
                EmpName: oView.byId("EmpName").getValue(),
                EmpAddr: oView.byId("EmpAddr").getValue()
            };

            OData.request({
                    requestUri: sServiceUrl + sCurrentPath.substr(1),
                    method: "GET",
                    headers: {
                        "X-Requested-With": "XMLHttpRequest",
                        "Content-Type": "application/atom+xml",
                        "DataServiceVersion": "2.0",
                        "X-CSRF-Token": "Fetch"
                    }
                },

                function(data, response) {
                    var oHeaders = {
                        "x-csrf-token": response.headers["x-csrf-token"],
                        "Accept": "application/json"
                    };

                    OData.request({
                            requestUri: sServiceUrl + sCurrentPath.substr(1),
                            method: "PUT",
                            headers: oHeaders,
                            data: oChangedData
                        },
                        // success
                        function(oData, oRequest) {
                            sap.m.MessageToast.show("Employee updated Successfully");
                            oEmployeeModel.refresh(true);
                        },
                        // error
                        function(oError) {
                            sap.m.MessageToast.show("Employee update Failed");
                        });
                },

                function(err) {
                    var request = err.request;
                    var response = err.response;
                    sap.m.MessageToast.show("Error in Get -- Request " + request + " Response " + response);
                });
        },

        deleteEmployee: function() {
            var oView = this.getView();
            var oEntry = {
                EmpId: oView.byId("EmpId").getValue()
            };

            OData.request({
                    requestUri: sServiceUrl + sCurrentPath.substr(1),
                    method: "GET",
                    headers: {
                        "X-Requested-With": "XMLHttpRequest",
                        "Content-Type": "application/atom+xml",
                        "DataServiceVersion": "2.0",
                        "X-CSRF-Token": "Fetch"
                    }
                },

                function(data, response) {
                    var oHeaders = {
                        "x-csrf-token": response.headers["x-csrf-token"],
                        "Accept": "application/json"
                    };

                    OData.request({
                            requestUri: sServiceUrl + sCurrentPath.substr(1),
                            method: "DELETE",
                            headers: oHeaders,
                            data: oEntry
                        },
                        // success
                        function(oData, oRequest) {
                            sap.m.MessageToast.show("Employee deleted Successfully");
                            window.location.reload(true);
                        },
                        // error
                        function(oError) {
                            sap.m.MessageToast.show("Employee deletion Failed");
                        });
                },

                function(err) {
                    var request = err.request;
                    var response = err.response;
                    sap.m.MessageToast.show("Error in Get -- Request " + request + " Response " + response);
                });
        },

        onItemPress: function(evt) {
            var context = evt.getSource().getBindingContext();
            sCurrentPath = context.getPath();
            sCurrentEmp = context.getProperty("EmpId");
        }

    });

});

源代码

Github: sap_openui5_practice_projects

参考资料

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,024评论 25 709
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,115评论 19 139
  • 属于电商的购物狂欢节,算是告一段落了,根据网上的通报,单单天猫的成交额就高达惊人的912亿。不管数据是不是准...
    清水出芙蓉阅读 334评论 0 0
  • 原野树,无人问津;秋风涩,枝枝叶落尽,耐岁寒。
    点点滴滴666阅读 369评论 0 1
  • 作为一名大学生,我们要学会管理好生活费用。大部分的学生还没有经济来源,都是靠父母给的生活费生活,所以更好好好对待它...
    iceyang阅读 320评论 2 0