I have created a javascript object and a function to build a new instance of the object. I now need to use this object on my page but am not having any luck, I feel that I am missing something.
JS Include File
function MyObject() {
this.ID = 0;
this.Name = "";
}
function GetObject(param1, param2) {
//ajax call to get json string
$.ajax({ //leaving out details this part works
success: function(data) {
var jsonData = $.parseJSON(data.d);
var myObj = new MyObject();
myObj.ID = jsonData[0].ID;
myObj.Name = jsonData[0].Name;
return myObj;
});
}
This call works fine, however when I try to access the data on the page I get undefined
Page
<script type="text/javascript">
$(function() {
var o = GetObject(1, 2);
});
</script>
I was able to get it to work by passing a DOM object through to the function and assigning it there.
function GetObject(param1, param2, domObj) {
//ajax call to get json string
$.ajax({ //leaving out details this part works
success: function(data) {
var jsonData = $.parseJSON(data.d);
var myObj = new MyObject();
myObj.ID = jsonData[0].ID;
myObj.Name = jsonData[0].Name;
domObj.text(myObj);
});
}
However this doesn’t work for my application as I’m pull a lot of objects and would like to just reference them on the page. What am I missing? Any help is greatly appreciated.
Just resign your
GetObjectlike this:Now call it like:
As, within
GetObjectthere is an AJAX request (asynchronous process) and object returned after ajaxsuccessfunction execute, so you need to take the help ofcallbackfunction.