0

嗨,我很新用cherrypy作为后端,fanytree作为前端。

这是我的代码的 fanytree 方面:

source: {
   url : '/test_data'
},

在cherrypy方面,我实现了名为test_data的函数

@cherrypy.expose
@cherrypy.tools.json_out()
def test_data(self, **kwargs):
  cherrypy.response.headers["Content-Type"] = "application/json"
  return '[ {"title":"abc", "folder": true, "key": "1", "children":[ {"title":"b","key":"2"}] }]'

所以我看到请求来自cherrypy

'GET /test_data?_=some number...

在浏览器上,我看到了返回对象,但检查失败:

if (typeof data === "string") {
      $.error("Ajax request returned a string (did you get the JSON dataType wrong?).");
 }

我在某处读到你需要内容类型为 json 但我已经有了。我错过了什么?

4

2 回答 2

1

内容类型没问题,但您返回的字符串不是有效的 json(例如,键必须用双引号括起来)。我建议将您的数据准备为字典列表,然后使用 'json.dumps()' 转换为 JSON。(也许 json_out 工具也是如此,但我猜即使那样你也应该返回一个字典列表而不是一个字符串。)

于 2014-09-18T19:18:55.090 回答
1

CherryPy JSON 输出工具,cherrypy.tools.json_out负责 MIME 并将您的数据转换为 JSON 字符串。因此,如果您使用它,该方法应如下所示:

@cherrypy.expose
@cherrypy.tools.json_out()
def test_data(self, **kwargs):
  return [{
    "title"    : "abc", 
    "folder"   : True, 
    "key"      : 1, 
    "children" : [{"title": "b", "key": 2}] 
  }]

否则,如果您想自己做,它将是:

import json

@cherrypy.expose
def test_data(self, **kwargs):
  cherrypy.response.headers["Content-Type"] = "application/json"
  return json.dumps([{
    "title"    : "abc", 
    "folder"   : True, 
    "key"      : 1, 
    "children" : [{"title": "b", "key": 2}] 
  }])

然后确保您已重新启动 CherryPy 应用程序,并查看 Web 开发人员工具或 FireBug 网络选项卡以验证响应标头和内容。

于 2014-09-19T10:19:52.680 回答