【发布时间】:2011-04-22 16:24:24
【问题描述】:
我正在使用 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)
我希望能够访问返回的 ID 的 HTML 页面:
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 方面的经验有限——我只使用它们将数据存储到服务器(a-la 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);
}
});
请注意,我将 dataType 指定为“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)
谢谢大家!
【问题讨论】:
-
查看 jQuerys getJSON 功能。它允许您自动将响应解析为 JSON 数据。 api.jquery.com/jQuery.getJSON
-
响应是什么样的?
标签: javascript jquery python ajax google-app-engine