How to return and use an array of strings from a jQuery ajax call?

I'm using Google App Engine (Python) along with jQuery for Ajax calls to the server. I have a page where I want to load up a list of strings in Javascript from an Ajax call to the server.
The server method I want to invoke:
class BrowseObjects(webapp.RequestHandler):
    def get(self):
        ids_to_return = get_ids_to_return()
        // TODO: How to return these ids to the invoking ajax call?
        self.response.out.write(ids_to_return)
The HTML page where I want to be able to access the returned ids:
    var strings_from_server = new Array();

    $.ajax({
        type: "GET",
        url: "/get_ids.html",
        success: function(responseText){
            // TODO: How to read these IDS in here?
            strings_from_server = responseText                
        },
            error: function (xhr, ajaxOptions, thrownError){
            alert(xhr.responseText);
        }
    });
My experience with Ajax is limited-- I've only used them to store data to the server (a-la POST commands) and so I really have no idea how to get data back from the server. Thanks in advance for all help

Answer is:


It's probably not the cleanest solution, but it will work. Since they are just IDs, it sounds like it's safe to push them directly into a string.
class BrowseObjects(webapp.RequestHandler):
    def get(self):
       ids_to_return = get_ids_to_return()

       response_html = '["'
       response_html += ids_to_return.join('","')
       # Edit: since my ids are Key objects (not strings)
       # I had to use the following instead:
       # response_html += '","'.join(map(str, ids_to_return))
       response_html += '"]'

       self.response.out.write(response_html)
and
var strings_from_server = new Array();

$.getJSON("/get_ids.html", function(responseData){

    strings_from_server = responseData;
});
You can check to see if the response was empty incase of an error, and you can use $.each to loop through the results.
I am using jQuerys getJSON feature to automatically parse the response. Since I'm just returning a json list, it will generate the array of data in the strings_from_server variable.

0 comments: