2013-11-23 267 views
1

在SO上有一个类似的题目问题,但它确实与我的问题没有任何关系。将JQuery数组传递给Flask变量

所以,我有一些JQuery数组,我在一个函数中创建。现在,我想在同一个函数中为这些JS数组设置一些烧瓶变量。我想这样做的原因是,我然后设置一个元素的href并路由我的用户。

下面是当前JS代码:

JQuery的

//Filter Search 
$(function() { 
    $('#filter_search').click(function() {    
     var entities = JSON.parse(JSON.stringify($('#filterform').serializeObject())).checkboxes; 
     var data = JSON.parse(JSON.stringify($('#filterform').serializeObject())).checkboxeslower; 
     if(typeof data == "string") { 
      data = $.makeArray(data); 
     } 

     //Here I want to set Flask variables like {{entities}} and {{data}} 

     //Then, I will call the next line 
     $("#filter_search").attr('href', "{{ url_for('filter_search', entities='{0}', data='{1}'.format(entities, data))}}"); 

     //Then, if all goes as planned, it will change the href and redirect the user to filtered_search 
    }); 
}); 

回答

1

你不能做到这一点,你所希望的方式,因为模板在服务器上运行,你的jQuery函数在客户端运行。

操作的顺序如下:

  • 客户端请求的页面
  • 服务器通过渲染模板的响应。在模板中的任何url_for()或其他Python代码运行在这个时候
  • 客户端接收的页面,并在其中
  • 你的jQuery函数最终执行执行JavaScript的,但那时已经太晚了改变url_for()输出。

你需要做什么才能使这项工作是建立在Javascript中的网址。

请参阅this answer,其中我提出了两个可能的解决方案来解决类似的问题。