Jump to content

JQuery Ajax call can't reference Global Variable


FrancisChung
 Share

Recommended Posts

Hi there,

I have a globally declared variable where I want to store a mapping table.

var _Pagelist=new Map();

The following Ajax call doesn't seem to set _Pagelist above. I think I have set the context parameter correctly to 'this'.

I've scoured through Stackoverflow and JQuery documentation but I can't figure out what is wrong.

 

Any pointers would be much appreciated.

Thanks

 

    if (!pagelist){
        
        SearchWaitDisplay(true);

        $.ajax({
            url: '/site/pagelist.php',
            context : this ,
            success: function(result) {
  		//here this._Pagelist is null, can't refer to This._Pagelist
                for (var x=0;x<result.length;x++) {
                    this._Pagelist.set(result[x].id, result[x].url);	//This will throw an error as _Pagelist is NULL.
                };
               	

                window.localStorage.setItem('pagelist', JSON.stringify(_Pagelist));      
                
                //The following will not update _Pagelist. Next 2 lines are just test code.
		this._Pagelist = result;
                window._Pagelist = result;
                                                  
                SearchWaitDisplay(false);


            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status + ' ' + thrownError);
            }
        });
    }
    else
    {
        //InitialiseSearchField(autocompletelist);
    }

 

Link to comment
Share on other sites

Where comes the this from? Is this a class? Complete code?

Usually it's because of the scope. Inside function you don't have this. Try this somewhere before ajax():

var that = this;

then in the callback functions:

that._Pagelist.set()

 

  • Like 1
Link to comment
Share on other sites

 Share

×
×
  • Create New...