从控制器odoo 9读取json数据

时间:2017-02-21 13:41:14

标签: json ajax odoo odoo-9

在控制器中我放了3个用户:

@http.route('/test_json', type="json", auth="public")
    def some_json(self):
        return json.dumps({"id": 1,"name": "Leanne Graham"},{"id": 2,"name": "Leanne Graham 2"},{"id": 3,"name": "Leanne Graham 3"})

的Ajax

$.ajax({
        type: "POST", 
        url: "/test_json", 
        async: false, 
        data: JSON.stringify({}), 
        contentType: "application/json", 
        complete: function (data) { 
              var mydata = JSON.stringify(data);
              alert(mydata)
              alert("How get only name in alert for user)
               },
        error: function () {
              alert("Error")
              }
         });

在警报获取

{"readyState":4,"responseText":"{\"jsonrpc\": \"2.0\", \"id\": null, \"result\": \"{\\\"id\\\": 1, \\\"name\\\": \\\"Leanne Graham\\\"}\"}","responseJSON":{"jsonrpc":"2.0","id":null,"result":"{\"id\": 1, \"name\": \"Leanne Graham\"}"},"status":200,"statusText":"OK"}

如何让所有用户(3个用户)和ajax警报显示每个人的名字?

3 个答案:

答案 0 :(得分:0)

为什么警告,使用日志和firebug

例如

$。AJAX({         键入:" POST",         url:" / test_json",         async:false,         data:JSON.stringify({}),         contentType:" application / json",         完成:功能(数据){

           },
    error: function () {
           console.log("error");
          }
     });

答案 1 :(得分:0)

阅读json.dumps方法documentation

作为方法的obj参数的字典对应于json对象,并且您只能有一个" root"当你有三个时,那里的物体。为了达到想要的目的,请尝试将所有词典用另一个词典括起来:

@http.route('/test_json', type="json", auth="public")
    def some_json(self):
        return json.dumps({{"id": 1,"name": "Leanne Graham"},{"id": 2,"name": "Leanne Graham 2"},{"id": 3,"name": "Leanne Graham 3"}})

答案 2 :(得分:0)

@http.route('/test_json', type="json", auth="public")
def some_json(self):
    return json.dumps({"ids":[{"id": 1,"name": "Leanne Graham"},{"id": 2,"name": "Leanne Graham 2"},{"id": 3,"name": "Leanne Graham 3"}]})

$.ajax({
        type: "POST", 
        url: "/test_json", 
        async: false, 
        data: JSON.stringify({}), 
        contentType: "application/json", 
        complete: function (data) { 
              var results = data[responseText"]["result"];
              var names = [];
              results.map(function(v){
                  names.push(v['name']);
              });
              alert(JSON.stringify(names));

        },
        error: function () {
              alert("Error")
              }
         });