【发布时间】:2014-12-04 11:04:11
【问题描述】:
我有一个来自 jQuery 的 AJAX 调用
function Admin_Ajax_pop_rows(){
$(document).ready(function(){
variable1= 'none';
$.ajax({
type: "POST",
url: "/someurl",
dataType: "json",
data: JSON.stringify({"variable1": variable1})
})
.success(function(data){
alert('success response: ' + data + ' number of rows : ');
})
.done(function(data){
alert ('rows : ' + data.return_rows);
MakeTablejQuery(data);
})
.fail(function(error){
alert('error status is : ' + error.status + ' text: ' + error.statusText + ' response text : ' + error.responseText);
});
});
}
在我的 Python 服务器代码中,我有
def post(self):
user_key = ndb.Key(self.user_model,'value')
user_key_parent = user_key.parent()
user_query = self.user_model.query(ancestor = user_key_parent).order(ndb.GenericProperty(sort_field))
query_data = user_query.fetch(i, projection=[ndb.GenericProperty('name'),ndb.GenericProperty('last_name'),ndb.GenericProperty('email_address')])
table_prop_data = { 'return_rows': 9 , 'return_cols' : 8}
return_table_prop_data = []
return_table_prop_data = json.dumps(table_prop_data)
return_data = []
return_data = json.dumps([dict(p.to_dict(), **dict(id=p.key.id())) for p in query_data],default = date_handler)
self.response.headers['content-type']=("application/json;charset=UTF-8")
self.response.out.write(return_data)
self.response.headers['content-type']=("application/json;charset=UTF-8")
self.response.out.write(return_table_prop_data)
我收到“200”错误,状态为“解析错误”
JSONLint 显示 JSON 错误
Parse error on line 74:
...662981951488 }]{ "return_cols":
---------------------^
Expecting 'EOF', '}', ',', ']'
我在 GAE 上使用 Webapp2
根据 Felix 的建议,我尝试使用以下内容创建字典 -
return_data = json.dumps({'table_props': dict(table_prop_data), 'query_data' : [dict(p.to_dict(), **dict(id=p.key.id())) for p in query_data],default = date_handler})
我收到语法错误。请帮我解决这个问题。这是我的 date_handler 函数。我需要它来处理查询中的日期时间字段。
def date_handler(obj):
return obj.isoformat() if hasattr(obj, 'isoformat') else obj
【问题讨论】:
-
顺便说一句,200 不是错误代码。那是 HTTP OK 代码。从 AJAX 调用者的角度来看,HTTP 调用是成功的,只是 JSON 格式不正确,正如下面@FelixKling 的回答中所述。
-
迈克-同意。 JSON 到达我的 javascript,并且在我的 Chrome 开发人员工具中,我能够获取对象列表 (query_data) 和变量 (table_prop_data)。但是 AJAX 以 .fail 返回,我无法在 .success 下执行该函数。您是正确的,因为 json 格式错误,所以 ajax 调用失败。
-
关于您的语法错误,您似乎没有正确关闭传递给
json.dumps的字典。您在],default=...)中的]之后缺少}。错误消息应该已经引导您朝着正确的方向前进。