functionretrieveToken(callback){varreq=newXMLHttpRequest;req.onload=function(){if(req.status=="200"){varresponse=JSON.parse(req.responseText);if(response.contents){callback(response.contents);// response contents is where the token is stored}};req.open("get","http://server.address/arcgis/tokens/?request=getToken&amp;username=username&amp;password=password&amp;expiration=60",true);req.send()}

I pass a parameter called callback - that’s a very important step, otherwise you would not be able to retrieve the token when you actually need it (AJAX stands for asynchronous). Now you just pass the token to the layer params like this: