jQuery 使用 SAPUI5 读取 REST 服务

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20099783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:58:28  来源:igfitidea点击:

Reading REST Service with SAPUI5

jqueryjsonrestsapui5

提问by DI MI

I am trying to access a REST Service with SAPUI5. I am sending a GET Request with the help of jQuery and expect a JSON respond, but all i get is an empty JSON Object. However the REST service tested with a RESTClient gives me the correct respond.

我正在尝试使用 SAPUI5 访问 REST 服务。我在 jQuery 的帮助下发送一个 GET 请求并期望一个 JSON 响应,但我得到的只是一个空的 JSON 对象。但是,使用 RESTClient 测试的 REST 服务给了我正确的响应。

Here is the code i am using sofar:

这是我使用的代码:

View

看法

sap.ui.jsview("sapui5_test.SAPUI5_Test", { 

    getControllerName : function() {
        return "sapui5_test.SAPUI5_Test";
    },

    createContent : function(oController) {

    var text = new sap.ui.commons.TextField( {  
        width : "100%"  
    }); 

// arrange controls on the page with a matrix layout  
    var ml = new sap.ui.commons.layout.MatrixLayout( {  
        columns : 2,  
        layoutFixed : true,  
        width : "500px"  
    }); 

    ml.addRow(new sap.ui.commons.layout.MatrixLayoutRow( {  
        cells : [  
            new sap.ui.commons.layout.MatrixLayoutCell( {  
                content : [ text ]  
            })]  
    }));

    var model = oController.initTodoModel();

    text.setValue(model.getJSON());
    return [ ml ];
    }   



});

Controller

控制器

sap.ui.controller("sapui5_test.SAPUI5_Test", {

initTodoModel : function() {  
            var oModel = new sap.ui.model.json.JSONModel();
            var aData = jQuery.ajax({
                type : "GET",
                contentType : "application/json",
                url : "http://sapm04.ibsolution.local:50000/demo.sap.com~d337_resttest_web/rest/todo/init/",
                dataType : "json",
                success : function(data,textStatus, jqXHR) {
                    oModel.setData({modelData : data}); 
                    alert("success to post");
                }

            });

            return oModel;  
        }
}

});

index.html

索引.html

<!DOCTYPE HTML>
<html>
<head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge">

      <script src="resources/sap-ui-core.js"
            id="sap-ui-bootstrap"
              data-sap-ui-libs="sap.ui.commons,sap.ui.table,sap.ui.ux3"
            data-sap-ui-theme="sap_goldreflection">
    </script>
    <!-- add sap.ui.table,sap.ui.ux3 and/or other libraries to 'data-sap-ui-libs' if required -->

    <script>
            sap.ui.localResources("sapui5_test");
            var view = sap.ui.view({id:"idSAPUI5_Test1", viewName:"sapui5_test.SAPUI5_Test", type:sap.ui.core.mvc.ViewType.JS});
            view.placeAt("content");
    </script>

</head>
<body class="sapUiBody" role="application">
    <div id="content"></div>
</body>

As already mentioned, when i run the same URL as in the jQuery in a RESTClient, i am getting a filled JSON Object as a result, however the result in the UI5 page is an empty JSON obejct {}.

如前所述,当我在 RESTClient 中运行与 jQuery 中相同的 URL 时,结果我得到了一个填充的 JSON 对象,但是 UI5 页面中的结果是一个空的 JSON 对象 {}。

I also tried the following solution:

我还尝试了以下解决方案:

var oModel = new sap.ui.model.json.JSONModel("http://sapm04.ibsolution.local:50000/demo.sap.com~d337_resttest_web/rest/todo/init/");

but this didn't help.

但这没有帮助。

回答by Mohamed Ali JAMAOUI

Well, the reason is obvious. the returnstatement in the controller finishes executing before the json object is filled with data. That's because the $.ajaxcall is asynchronous which means that JavaScript does the call to the backend server and doesn't wait till the answer is sent, rather JavaScript goes straight to the next instruction which is return oModelbefore having the oModelfilled with data. If you make a synchronousrequest to the backend your problem will be resolved, you can do that this way:

嗯,原因很明显。return控制器中的语句在 json 对象填充数据之前完成执行。那是因为$.ajax调用是异步的,这意味着 JavaScript 会调用后端服务器,并且不会等到响应发送,而是 JavaScript 直接执行下一条指令,即return oModeloModel填充数据之前。如果您向后端发出同步请求,您的问题将得到解决,您可以这样做:

 sap.ui.controller("sapui5_test.SAPUI5_Test", {

 initTodoModel : function() {  
        var oModel = new sap.ui.model.json.JSONModel();
        var aData = jQuery.ajax({
            type : "GET",
            contentType : "application/json",
            url : "http://sapm04.ibsolution.local:50000/demo.sap.com~d337_resttest_web/rest/todo/init/",
            dataType : "json",
            async: false, 
            success : function(data,textStatus, jqXHR) {
                oModel.setData({modelData : data}); 
                alert("success to post");
            }

        });

        return oModel;  
    }
  }

 });

However, using synchronouscalls is not recommendedbecause it will halt the application until the request is done.

但是,不建议使用同步调用,因为它会在请求完成之前暂停应用程序。

Why you shouldn't use synchronous requests?

为什么不应该使用同步请求?

Just imagine halting your application till the call is finished. That might not be a great deal for few requests but if you have a large application that requires a lot of interaction with a backend data provider then this will be a major issue.

想象一下,在呼叫完成之前暂停您的应用程序。对于少数请求,这可能不是什么大问题,但如果您有一个大型应用程序,需要与后端数据提供者进行大量交互,那么这将是一个主要问题。

Design improvement suggestion:

设计改进建议:

If it's up to me, I would design the application so that I am able to register callback functionsinto the ajax request. So the application would follow a chain of responsibility like design pattern and when the data is ready, the module depending on it will be executed and it won't halt the other modules of the application.

如果由我决定,我会设计应用程序,以便我能够将回调函数注册到 ajax 请求中。因此,应用程序将遵循设计模式之类的责任链,当数据准备就绪时,将执行依赖于它的模块,并且不会停止应用程序的其他模块。

In simple terms, do whatever you want to do with the data by calling a function within the success function and not outside the $.ajaxcall.

简单来说,通过在成功函数内而不是在$.ajax调用外调用函数来对数据做任何你想做的事情。