Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Well, the reason is obvious. the return statement in the controller is done before the json object is filled with data. That's because the $.ajax call 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 oModel before having the oModel filled with data. If you make a synchronous request to the backend your problem will be resolved, you can do that this way: </p> <pre><code> 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; } } }); </code></pre> <p>However, using synchronous calls is not recommended, 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. </p> <p>If it's up to me I would design the application so that I am able to register callback functions into 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. </p> <p>In simple terms, do whatever you want to do with the data by calling a function within the success function and not outside the ajax call. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload