简体   繁体   中英

Javascript passing object from include file to page

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 GetObject like this:

function GetObject(param1, param2, callback) {
    //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;

        // pass myObj via callback function parameter
        return callback( myObj );
    });
}

Now call it like:

$(function() {
     var  o = {};
     GetObject(1, 2, function(response) {
         o = response;
     });
});

As, within GetObject there is an AJAX request (asynchronous process) and object returned after ajax success function execute, so you need to take the help of callback function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM