我正在使用Ajax Form jQuery插件从服务器获取JSON:
/**
* Helper function for the jQuery AJAX form plugin.
*/
function bindOnSuccess(form, callback) {
form.ajaxForm({
dataType: 'json',
success: function (response, status, xhr, $form) {
callback(response);
}
});
}
用法:
bindOnSuccess($('#course-search'), function(response) {
if (!response) {
$("#system-status").text("Sorry, no course could be found for that search.");
}
else {
$(".dept-code").text(response['course']['_dept_code']);
$(".course-number").text(response['course']['_number']);
$(".course-title").text(response['course']['_title']);
$("#div-unparsed-pre-reqs").show();
$("#unparsed-pre-reqs-teaser").show();
$("#unparsed-pre-reqs").text(response['course']['_unparsed_pre_reqs']).hide();
$("#td-required-for").text(response['analysis']['cRequiredFor']);
loadNewJson(response['graph']);
}
});
正确评估JSON。然而,部分原因让我感到惊讶:
{"course": { 'foo': 'bar', /* data */},
"analysis": { 'baz': 'odp', /* data */},
"graph": "[{\"adjacencies\": [], \"id\": 2539, \"name\": \"BEE 3310: Bio-Fluid Mechanics\"}, {\"adjacencies\": [{\"nodeTo\": 2539, \"data\": {\"$direction\": [3332, 2539]}}], \"id\": 3332, \"name\": \"UNKNOWN 9999: UNKNOWN\"}]"}
为什么response['course']
和response['analysis']
被解析,但response['graph']
仍然是字符串?
更新:我刚试了一遍,但它确实有效。我不确定我有什么改变。奇
服务器代码(Python)看起来像这样:
result = {'course': dict_course, 'analysis': analysis, 'graph': jit_graph_data}
self.response.out.write(json.dumps(result))
答案 0 :(得分:0)
获得该输出的唯一方法是,如果jit_graph_data
已经是JSON,或者因为它是在管道中较早的某处编码,或者是因为从源中提取它时从未解码过。
答案 1 :(得分:0)
要添加到Ignacio's answer,您可以修复服务器端代码以使用此功能:
result = {'course': dict_course, 'analysis': analysis, 'graph': json.loads(jit_graph_data)}
self.response.out.write(json.dumps(result))