I'm trying to learn JQuery and I have a web page where I've created a function named "getUserList"
.
All this does is performs an AJAX call to the server which returns a JSON string that looks like this: {"code":"1","message":["Alan"]}
So we have message which contains an array of one item, in this case.
The function looks like this:
$.fn.getUserList = function(){
//Call the server and get the list of users currently logged in
var list;
$.ajax({
type: "GET",
url: "/ChatEngine/ChatServlet/users/list?roomId=" + roomID,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if (msg.code=="1")
{
console.log(msg.message);
list = msg.message;
}
else
{
alert("Unable to obtain user list. code: " + msg.code + " message: " + msg.message);
}
},
error: function(err) {
alert('Get User List Error:' + err.responseText + ' Status: ' + err.status);
}
});
return list;
}
In another function I make the call to getUserList()
like so:
var list = $(document).getUserList();<br>
for(var i = 0; i < list.length; i++) { ... }<br>
But I keep getting an error saying that list is undefined. As you can see from the function that I am returning the array and according to FireBug, the console is recording the existence of the array:
So, why is list undefined? One other question...in order to make a function call I have to keep using the syntax: $(document).somefunctionname();
Why is it I can't just write: somefunctionname();
Why do I always need to prepend the call with $(document)
? If I don't, I keep getting an error saying that the function doesn't exist, which isn't true.
Please advise.
Alan