cancel
Showing results for 
Search instead for 
Did you mean: 

[UI5] How to check if a json file exist?

former_member197944
Active Participant
0 Kudos

I would like to load a JSONModel from a local .json file:

var myModel = new sap.ui.model.json.JSONModel();
myModel.loadData("/myApp/data/Products.json", "", false);

But if there's no such json file an error will be thrown:

JSONModel-dbg.js:202 Uncaught TypeError: Cannot read property 'status' of undefined
    at constructor.<anonymous> (JSONModel-dbg.js:202)
    at Object.error (ClientModel-dbg.js:106)
    at p (jquery-dbg.js:3187)
    at Object.fireWith [as rejectWith] (jquery-dbg.js:3317)
    at h3 (jquery-dbg.js:8787)
    at XMLHttpRequest.<anonymous> (jquery-dbg.js:9151)
    at Object.send (jquery-dbg.js:9203)
    at Function.ajax (jquery-dbg.js:8684)
    at constructor.d._ajax (ClientModel-dbg.js:114)
    at constructor.<anonymous> (JSONModel-dbg.js:212)

So I would like to check if there exist such a json file. But how could I do it? Thank you so much!

Accepted Solutions (1)

Accepted Solutions (1)

Ivan-Mirisola
Product and Topic Expert
Product and Topic Expert
0 Kudos

Hi Cong,

Have you tried this already?

var url = '/myApp/data/Products.json';
$.ajax({
	url:   url,
	dataType: “json”,
	cache: false,
	success: function(data){
		myModel.setData(data);
	},
	error: function( jqXHR, textStatus, errorThrown){
		alert("does not exist" + textStatus.toString());
	}
});

Jquery is capable of retrieving data from services as well as files, according to the API. This way you could ensure your model will not be empty, unless the file isn't there.

You could also use JQuery's getJSON method as well:

// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.getJSON( "example.json", function() {
  console.log( "success" );
})
  .done(function() {
    console.log( "second success" );
  })
  .fail(function() {
    console.log( "error" );
  })
  .always(function() {
    console.log( "complete" );
  });
 
// Perform other work here ...
 
// Set another completion function for the request above
jqxhr.complete(function() {
  console.log( "second complete" );
});

Regards,
Ivan

former_member197944
Active Participant
0 Kudos

Hi Ivan,

Thank you so much! It works!

Cong

Answers (0)