遇到Jquery post和Flask的麻烦

时间:2015-01-22 23:22:56

标签: jquery flask

在我的html页面中,我有

    <button id = "mybutton" class = "btn" type="submit" >Go</button>

我在页面上的js是

$("#mybutton").click(function(){
    $.post('{{ url_for("fromserver") }}',
            {name: "Fred"}, 
            function(data){ alert(data); },
            "json"
          );
 });

&#34; fromserver&#34;的视图是

@app.route('/fromserver', methods=['GET', 'POST'])
def fromserver():
    print request
    return "astring"

如何从视图中访问name数据?

2 个答案:

答案 0 :(得分:0)

我使用的一些示例代码。

@api.route('/data_management/search/Booking/', methods=['POST'])
@permission_required(Permission.VIEW_DATA)
def get_management_search_booking_string():

    json = request.get_json(silent=False, force=True)
    q = ''.join(('%',json['q'],'%'))
    page_limit = try_parse_int(json['page_limit'])
    page = try_parse_int(json['page'])

的javascript

function GetBookings(term, pageLimit, page) {
  term = typeof term !== 'undefined' ? term : "";
  pageLimit = typeof pageLimit !== 'undefined' ? pageLimit : 999999;
  page = typeof page !== 'undefined' ? page : 1;
  var query = { q: term, page_limit: pageLimit, page: page };
  var result = [{id: "0", text: "-- Not set --"}];
  $.ajax({
    url: '/data_management/search/Booking/',
    type: 'POST',
    data: JSON.stringify(query),
    dataType: 'JSON',
    async: false,
    success: function(data) {
      for(var i = 0; i < data.bookings.length; i++) {
        result.push({id: data.bookings[i].id, text: data.bookings[i].name});
      }
    }
  });
  return result;
}

答案 1 :(得分:0)

我设法使用$.ajax()代替$.post()并设置contentType来解决此问题:

$("#mybutton").click(function(){
    $.ajax({
        type: 'POST',
        url: '{{ url_for("fromserver") }}',
        data: JSON.stringify({name:'Fred'}),
        dataType: 'json',
        contentType: 'application/json; charset=utf-8'
    })
});

然后在我看来

x = request.get_json()
print x['name']

给了我想要的结果。出于某种原因x.name没有工作。