【问题标题】:Read json data from controller odoo 9从控制器odoo 9读取json数据
【发布时间】:2017-02-21 13:41:14
【问题描述】:

在控制器中我放置了 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({
        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 警报显示名称?

【问题讨论】:

    标签: json ajax odoo odoo-9


    【解决方案1】:

    为什么要提醒,使用日志和萤火虫

    例子

    $.ajax({ 类型:“发布”, 网址:“/test_json”, 异步:假, 数据:JSON.stringify({}), 内容类型:“应用程序/json”, 完成:函数(数据){

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

    【讨论】:

      【解决方案2】:

      阅读json.dumps方法documentation

      作为该方法的obj 参数的字典对应于一个json 对象,而您只有一个“根”对象,而您拥有三个。为了实现你想要尝试用另一个字典封闭你所有的字典:

      @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"}})
      

      【讨论】:

        【解决方案3】:
        @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")
                      }
                 });
        

        【讨论】:

        猜你喜欢
        • 2014-07-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-25
        • 2019-11-10
        相关资源
        最近更新 更多