我在google上搜索有关如何在odoo上创建json视图的文档,但是找到了litle信息
我需要创建一个json视图来从javascript访问。
我试着这样:
@http.route('/test/status/<name>', auth='public', type='json')
def temp(self, name,**kwargs):
return [{'status': 'test',
}]
Javascript代码:
function check_status() {
var name = $('#name').val();
$.getJSON("/test/status/" + name +"/",
function(data){
var status = data.status;
$('#msg').text(status);
});
};
我收到以下错误:
<function temp at 0x7f1a8b7d5140>, /test/status/lego/: Function declared as capable of handling request of type 'json' but called with a request of type 'http'
请帮助我卡住
[编辑回答@ odoo_user2]
function json_function_name() {
odoo.define('custom_webpage.my_js', function (require) {'use strict';
var ajax = require('web.ajax');
ajax.jsonRpc('/pa/get_models/' + variable_id, 'call', {}).then(function (data) {
if (data.models == false) {
} else {
// load models
for (var i = 0; i < data.models.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = data.models[i][1];
opt.value = data.models[i][0];
sel_models.appendChild(opt);
}
}
});
})
}
}
这是我使用的javascript函数,以及控制器:
@http.route('/pa/get_models/<brand_id>', auth='none', type='json',website=True)
def get_models(self,brand_id**kwargs):
cr = http.request._cr
res = utils.get_models(cr,int(brand_id))
return {'models': res,}
答案 0 :(得分:2)
目前我正在使用返回json的python web控制器。我给你一些例子:
from openerp import http, _
from openerp.http import request
import json
class ClassName(http.Controller):
@http.route('url', auth='user', type="json")
def className(self, **kw):
cr = request.cr
context = request.context
uid = request.uid
user = request.env['res.users'].sudo().browse(uid)
# now in kw you have all arguments from your post request
# and finally when you will finish work with data and want to
# return json return like that
return json.dumps(res)
# where res is dictionary
另外我建议在python web控制器中进行输入验证更安全! 将此答案标记为正确答案,这就是您所需要的。 (我认为这就是你需要的)
答案 1 :(得分:1)
而不是$.getJSON
在odoo8中使用openerp.jsonRpc
,在odoo9中使用var ajax = require('web.ajax');
ajax.jsonRpc
。
答案 2 :(得分:0)
检查此JS调用[1]
openerp.jsonRpc('/website/check_gengo_set', 'call',[...]
及其控制器[2]
@http.route('/website/check_gengo_set', type='json', auth='user', website=True)
这样可行,所以出于某种原因,你可能没有做正确的JSON请求。
此处触发错误[3]并弹出:请求与类型不匹配。
请注意jsonrpc
来电[4]:
openerp.jsonRpc = function(url, fct_name, params, settings) {
return genericJsonRpc(fct_name, params, function(data) {
return $.ajax(url, _.extend({}, settings, {
url: url,
dataType: 'json',
type: 'POST',
data: JSON.stringify(data, date_to_utc),
contentType: 'application/json'
}));
});
};
无论如何,如果你想使用那个JS,也许你可以尝试w / type="http"
并自己转储json。这应该有用。
[1] https://github.com/OCA/OCB/blob/8.0/addons/website_gengo/static/src/js/website_gengo.js#L42
[2] https://github.com/OCA/OCB/blob/8.0/addons/website_gengo/controllers/main.py#L21
[3] https://github.com/OCA/OCB/blob/8.0/openerp/http.py#L290
[4] https://github.com/OCA/OCB/blob/8.0/addons/web/static/src/js/openerpframework.js#L859