我正在尝试构建一个页面,当用户按下一个按钮时,变量最初为0,增量为1.然后使用jQuery AJAX将该数字异步发送到服务器。
到目前为止我所拥有的是:
在我的__init__.py
文件中:
def main(global_config, **settings):
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind = engine)
Base.metadata.bind = engine
config = Configurator(settings = settings)
config.include('pyramid_jinja2')
config.add_static_view('static', 'static')
config.add_static_view('scripts', 'scripts')
# Removed the other views
config.add_route("declare_usage", '/user/{user_id}/{address_id}/declare')
config.add_route("declare_usage_json",'/user/{user_id}/{address_id}/declare.json')
config.scan()
我的HTML + Jinja2:
#Removed code for simplicity
<div id="button_add">Add</div>
{{val}}
我的JS:
$(document).ready(function(){
var room = 0;
jQuery.ajax({type:'POST',
url: '/user/1/5/declare', #I use a direct user ID and a direct address ID as I'm not sure how to send this to JS from Pyramid ... yet :).
data: JSON.stringify(room),
contentType: 'application/json; charset=utf-8'});
$('#button_add').click(function(){
room = room + 1;
});
});
我的观看代码:
@view_config(route_name = 'declare_usage', renderer = 'declara.jinja2')
@view_config(route_name = 'declare_usage_json', renderer = 'json')
def declara_consum(request):
#Removed code for simplicity
val = request.POST.get('room') #I get a "None value in my html" if I change to request.json_body -> I get an error that there is no json to be parsed.
return { 'val' : val }
当我打开调试器时,POST请求成功且没有数据,在页面上我得到2个'val'选项:
None
- &gt;当我使用val = request.POST.get('room')ValueError: No JSON object could be decoded
- &gt;当我使用val = request.json_body 此外,如果在我的JS中我将更改网址更改为/user/1/5/declare.json
和/或将数据更改为{'room' : room}
有人可以指出我做错了吗?
答案 0 :(得分:0)
你不需要另一条路线declare_usage_json
,只需要另外两个这样的功能
@view_config(route_name = 'declare_usage', renderer = 'declara.jinja2')
def declara_consum(request):
# this will response to your jinja2
return { 'val' : val }
@view_config(route_name = 'declare_usage', xhr=True, renderer = 'json')
def declara_consum_ajax(request):
# this will response to your asynchronously request
val = request.POST.get('room')
return { 'val' : val }
当您使用ajax发送请求时,这将转到第二个函数。
$.ajax({
type: 'POST',
url: '/user/1/5/declare',
data: {'room' : room},
dataType: 'json'
}).done(function(response){
// update your data at html
});