Javascript 金字塔json视图ajax调用
我以前从未真正使用过ajax,因此请您在回答中详细说明 我有一个金字塔应用程序,我想通过ajax加载信息,因为预加载是不可行的。因此,我想通过金字塔视图加载所需的信息,但我不确定如何执行此操作。Javascript 金字塔json视图ajax调用,javascript,python,ajax,json,pyramid,Javascript,Python,Ajax,Json,Pyramid,我以前从未真正使用过ajax,因此请您在回答中详细说明 我有一个金字塔应用程序,我想通过ajax加载信息,因为预加载是不可行的。因此,我想通过金字塔视图加载所需的信息,但我不确定如何执行此操作。 我需要获取的信息位于MySQL数据库中,因此我想我需要将鼠标单击事件对象ajax\u id导入views.py以进行查询。(我可以毫无问题地获取ajax\u id) 在my views.py中,我有: @view_config(route_name="info_ajax",renderer="json"
我需要获取的信息位于MySQL数据库中,因此我想我需要将鼠标单击事件对象
ajax\u id
导入views.py以进行查询。(我可以毫无问题地获取ajax\u id)
在my views.py中,我有:
@view_config(route_name="info_ajax",renderer="json")
def info_ajax(self):
#for the sake of this example, lets just return the information from the mouse click event
A = ajax_id #is the id of the mouse click event
B = ajax_name #is the name of the mouse click event
return {
'a' : A,
'b' : B,
}
我通常会预加载所有信息,但在本例中这需要很长时间,因此我不能在views.py中列出MySQL查询,然后执行window.coords=${a | query_list}代码>在my.mak文件中
我想在JavaScript代码中导入a
和b
作为变量,这样我就可以再次使用它们,而不必在需要时重新加载它们。我该怎么做呢?已经有一个官方的金字塔教程,提供了足够的背景知识来解决基本的AJAX任务
你需要更多的教程吗
我最喜欢的高级教程是ToDoPyramid(Github分叉)
所以我想出了办法:
在pyramid view.py中:
@view_config(route_name="info_ajax",renderer="json")
def info_ajax(self):
#for the sake of this example, lets just return the information from the mouse click event
A = self.request.POST.get('ajax_id') #is the id of the mouse click event
B = self.request.POST.get('ajax_name') #is the name of the mouse click event
return {
'ID' : A,
'Name' : B,
}
在JS中:
$.ajax({
type: "POST",
url: "details",
dataType: "json",
data: {
'ajax_id': iID,
'ajax_name': sName,
},
success: function(data) {
iReturned_value = data.ID;
},
})
通常,您返回一个字典或一些可以从使用JSON呈现程序的视图序列化为JSON的内容。渲染器将转换为JSON本身。对您来说很容易,并且更容易在测试用例中进行测试。