我正在尝试使用SAPUI5访问REST服务.我在jQuery的帮助下发送了一个GET请求并期望
JSON响应,但我得到的只是一个空的JSON对象.但是,使用RESTClient测试的REST服务给了我正确的响应.
这是我使用sofar的代码:
视图
- 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 ];
- }
- });
调节器
- 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
- <!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>
如前所述,当我在RESTClient中运行与jQuery中相同的URL时,我得到一个填充的JSON对象,但是UI5页面中的结果是一个空的JSON obejct {}.
我也尝试了以下解决方案:
- var oModel = new sap.ui.model.json.JSONModel("http://sapm04.ibsolution.local:50000/demo.sap.com~d337_resttest_web/rest/todo/init/");
但这没有帮助.
解决方法
嗯,原因很明显.控制器中的return语句在json对象填充数据之前完成.那是因为$.ajax调用是异步的,这意味着JavaScript会对后端服务器进行调用,并且不会等到发送答案,而是直接转到下一条指令,该指令在oModel填充数据之前返回oModel .如果您向后端发出同步请求,您的问题将得到解决,您可以这样做:
- sap.ui.controller("sapui5_test.SAPUI5_Test",{
- initTodoModel : function() {
- var oModel = new sap.ui.model.json.JSONModel();
- var aData = jQuery.ajax({
- type : "GET",async: false,jqXHR) {
- oModel.setData({modelData : data});
- alert("success to post");
- }
- });
- return oModel;
- }
- }
- });
但是,建议不要使用同步调用,只需假设在调用完成之前暂停应用程序.对于少数请求而言,这可能不是很多,但如果您有一个需要与后端数据提供程序进行大量交互的大型应用程序,那么这将是一个主要问题.
如果由我决定,我会设计应用程序,以便我能够将回调函数注册到ajax请求中.因此,应用程序将遵循设计模式等责任链,当数据准备就绪时,依赖于它的模块将被执行,并且它不会停止应用程序的其他模块.