如何使用sapui5通过REST服务发送json模型

时间:2015-01-19 16:48:26

标签: json rest model sapui5

我正在使用SAPUI5,我有一个XML表单,我想使用Json Model将数据发送到我的REST服务。

我正在使用SAPUI5 MVC模型制作我的应用程序。

如何使用REST和JSON将数据发送到我的服务器?

sap.ui.controller("controller.NewTicket", {

    onInit: function() {
        this.router = sap.ui.core.UIComponent.getRouterFor(this);
        this.router.attachRoutePatternMatched(this._handleRouteMatched, this);
    },
    _handleRouteMatched:function(evt){
        if("NewTicket" !== evt.getParameter("name")){
            return;
        }
        var id = evt.getParameter("arguments").id;
        var model = new sap.ui.model.json.JSONModel({id:id});
        this.getView().setModel(model,"data");
    },


    enviar:function() {
        jQuery.sap.require("sap.m.MessageBox");

        // open a fully configured message box
        sap.m.MessageBox.show("Confirmar a abertura do chamado?",
                sap.m.MessageBox.Icon.QUESTION,
                "Confirmar",
                [sap.m.MessageBox.Action.YES, sap.m.MessageBox.Action.NO], 
                function(sResult) {
            if(sResult == sap.m.MessageBox.Action.YES)    
            {
                var oModel = new sap.ui.model.json.JSONModel();
                var aData = jQuery.ajax({
                    type : "POST",
                    contentType : "application/json",
                    url : "http://192.168.0.32:9082/maxrest/rest/mbo/sr/?description="+ **deviceModel.sr.description** +"&_format=json&_compact=true&_verbose=true",
                    dataType : "json",
                    async: false, 
                    success : function(data,textStatus, jqXHR) {
                        oModel.setData({modelData : data}); 
                        sap.m.MessageBox.show("ABRIU");
                    },
                    error : function(data,textStatus, jqXHR) {
                        oModel.setData({modelData : data}); 
                        sap.m.MessageBox.show(textStatus);
                    }
            })}
            else 
           {
           }
        },
                sap.m.MessageBox.Action.YES);

        var deviceModel = new sap.ui.model.json.JSONModel({
            sr : [{
                description: "",
                long_description: ""
            }]});
        deviceModel.setDefaultBindingMode("TwoWay");
        sap.ui.getCore().setModel(deviceModel);

        jQuery.sap.require("sap.m.MessageToast");
        sap.m.MessageToast.show(deviceModel.getData().sr.description);
    }

});

观点......

<mvc:View xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m" xmlns:co="sap.ui.commons"
xmlns:f="sap.ui.layout.form" xmlns:core="sap.ui.core" controllerName="com.maximo.controller.NewTicket">

<Page id="NewTicket" enableScrolling="true" title="{i18n>newTicket}" >
    <content>
            <f:SimpleForm >
                <core:Title level="H5"
                    text="O chamado será aberto em seu nome e você será o usuário afetado"/>
                <Label text="Resumo"/>
                <Input type="Text" maxLength="100" value="{/sr/description}"/>      
                <Label text="Detalhes"/>      
                <TextArea height="50%" cols="800" value="{/sr/long_description}"/>  
            </f:SimpleForm>
    </content>
    <customHeader>
        <Bar>
            <contentLeft>           
                <Button icon="sap-icon://nav-back" press="voltarMenu"/>
            </contentLeft>
            <contentMiddle>
                <Label text="{i18n>newTicket}"/>
            </contentMiddle>
        </Bar>
    </customHeader>
    <footer>
        <Bar>
            <contentMiddle>
                <Button id="btnSend" text="{i18n>send}" press="enviar" icon="sap-icon://add-activity-2"/>
            </contentMiddle>
        </Bar>
    </footer>
</Page>

1 个答案:

答案 0 :(得分:1)

根据我的经验,我发现使用“JSON”类型的OData模型更容易。

        var user = applicationContext.registrationContext.user;
        var password = applicationContext.registrationContext.password;
        var uri = "http://" + user + ":" + password + "@" + applicationContext.registrationContext.serverHost + ":8080/" + appId + "/"
        var headers = {
                //"Authorization" : "Basic " + btoa(applicationContext.registrationContext.user + ":" + applicationContext.registrationContext.password),
                "X-SMP-APPCID"  : applicationContext.applicationConnectionId
            };

        console.log("Try comunicating the first time");
        var oModel = new sap.ui.model.odata.ODataModel(uri, {json : true}, user, password, headers, false, false, false);

        oModel.setHeaders(headers);
        oModel.read("/Brand", onSuccess);   

                function onSuccess(result) {
                    sap.ui.getCore()....getView().getModel("Brands").setData(result);
                    };

这就是我如何处理我的所有请求,手动或自动(关于手动事件或页面事件)。

对于“post”事件,我使用了令牌fech:

     oModelRequest.setHeaders({ 
                "Access-Control-Allow-Origin" : "*",
                "Content-Type": "application/x-www-form-urlencoded",
                "X-CSRF-Token":"Fetch" 
                });

            // Declare a variable to handle the security token
            var token;

            // Create a read request to retreive the X-CSRF token
            oModelRequest.read('/Brand', null, null, false, 
                    function(oData, oResponse) {
                        if (oResponse.headers['x-csrf-token'] == undefined) {
                            //alert("Error on read process. No token ! Check read !");
                        }
                        token = oResponse.headers['x-csrf-token'];
                        }, 
                    function() {
                            alert(oModeli18n.getProperty("Brand_token_error"));
                            }
                        );

然后我使用“创建”方法执行实际的“POST”:

        // Set POST request header using the X-CSRF token
        oModelRequest.setHeaders({
            "X-Requested-With": "XMLHttpRequest",
            "Content-Type": "application/json",
            "DataServiceVersion": "2.0",
            "Accept": "application/atom+xml,application/atomsvc+xml,application/xml",
            "X-CSRF-Token": token 
            });

        // Call the create request

        oModelRequest.create('/Brand', requestData, null, 
                  function(oData, oResponse) {
                    alert (Success);},
                  function(oData) {                     
                    alert(Error));
                    alert(oData.response.body);}
                      );