SAPUI5 JSONModel and JSONP

2020-07-24 05:59发布

问题:

I have a JSONP-based REST service which I need to load into a JSONModel.

URL: http://pipes.yahoo.com/pipes/pipe.run?_id=eb8dcd1d84e4aa323378ce219683878a&_render=json&_callback=bbcModelLoaded (_callback parameter is the JSONP function to be called)

What is the preferred way of creating a JSONModel from this?

I would prefer to avoid handling the AJAX call myself.

Error if you create a JSONModel with a JSONP url is:

The following problem occurred: parsererror - bbcModelLoaded({"count":52,...

回答1:

There is no need for $.getJSON, a JSONP model or any other code adoption.

This actually works out of the box:

new sap.ui.model.json.JSONModel("http://pipes.yahoo.com/pipes/pipe.run?_id=eb8dcd1d84e4aa323378ce219683878a&_render=json&_callback=?");

Live example here: http://jsbin.com/babiqoze/1/edit?html,output

The important thing is that you set the value of the callback parameter to "?" so that jQuery detects it and handles it as an JSONP request. http://api.jquery.com/jquery.getjson/#jsonp



回答2:

Simplest solution found so far is to use JQuery's getJSON

    $.getJSON("http://pipes.yahoo.com/pipes/pipe.run?_id=eb8dcd1d84e4aa323378ce219683878a&_render=json&_callback=?", function(results) {
        oModel= new sap.ui.model.json.JSONModel(results);
    }

Maybe we should add a JSONPModel which just does just this to #sapui5/openui5 ?



回答3:

Would be nice to have a JSONP model in sapui5. I am also not sure how to handle timeouts, callbacks and errors? Also parameter generation could me more dynamic.

Something like:

var mParameters = {
"Key1" : "Value1",
"Key2" : "Value2",
...
}
var oModel = new JsonpModel(sURL, mParameters, fCallback, fTimeout);


标签: sapui5