如何从jQuery ajax调用中返回并使用字符串数组?

2 投票
2 回答
2908 浏览
提问于 2025-04-16 05:11

我正在使用Google App Engine(Python)和jQuery来进行Ajax调用,目的是和服务器进行交互。我有一个页面,想通过Ajax从服务器加载一串字符串到JavaScript中。

我想调用的服务器方法是:

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)

我想在这个HTML页面上访问返回的ID:

    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);
        }
    });

我对Ajax的了解不多——我只用过它来把数据存储到服务器(像是POST命令),所以我真的不知道怎么从服务器获取数据。提前感谢大家的帮助。

编辑:我的最终答案:

我改用了完整的Ajax调用(以防止跨域请求),并且处理了“错误”回调。我的客户端方法现在看起来是:

         $.ajax({
            type: "GET",
            dataType: "json",
            url: "/get_ids.html",
            success: function(reponseText){
                strings_from_server = responseText                
            },
            error: function (xhr, ajaxOptions, thrownError){
                    alert(xhr.responseText);
            }
        });

注意我把数据类型指定为'json'。
而我最终的服务器函数,结合sahid的回答,变成了:

class BrowseObjects(webapp.RequestHandler):
    def get(self):
        ids_to_return = get_ids_to_return()
        # Note: I have to map all my objects as `str` objects
        response_json = simplejson.dumps(map(str, ids_to_return))
        self.response.out.write(response_json)

谢谢大家!

2 个回答

6

Google AppEngine 提供的 SDK 中包含了一个叫 "simplejson" 的库,这个库是由 django 提供的。

from django.utils import simplejson

所以你的处理程序可能就很简单:

from django.utils import simplejson
class BrowseObjects(webapp.RequestHandler):
    def get(self):
       ids_to_return = get_ids_to_return()
       response_json = simplejson.dumps (ids_to_return)
       self.response.out.write(response_json)

关于 ajax/rpc 有一篇不错的文章,可以参考一下:http://code.google.com/appengine/articles/rpc.html

3

这可能不是最完美的解决方案,但它可以正常工作。因为它们只是一些ID,所以直接把它们放进一个字符串里应该是安全的。

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)

还有

var strings_from_server = new Array();

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

    strings_from_server = responseData;

});

你可以检查一下响应是否为空,以防出现错误,并且可以使用 $.each 来遍历结果。

我正在使用 jQuery 的 getJSON 功能来自动解析响应。因为我只是返回一个 JSON 列表,所以它会在 strings_from_server 变量中生成数据数组。

撰写回答