在烧瓶认为AJAX发布数据烧瓶、数据、AJAX

2023-09-10 13:35:52 作者:再也不见

下面是我的看法功能

@app.route('/share', methods=['GET', 'POST'])
def share():
    form = ShareForm(request.form)
    if request.method == 'POST':
        title = form.title.data
        body = form.body.data
        share_id = form.share_id.data
        print 'form data %s %s %s' % (title, body, share_id)
        if not share_id:
            share = Shares(title, body, 'PUBLISHED', current_user.id)
            db.session.add(share)
            db.session.commit()
            form.share_id.data = share.id
        return jsonify({'status': 204, 'body': {'status': True}})
    else:
        return render_template('share.html', form=form)

在code为Ajax POST请求

The code for ajax post request

<script>
    $(function(){
      $('#share').on('click', function(e){
        e.preventDefault(); // preventing default click action
        $.ajax({
          url: '/share',
          type: 'post',
          contentType: "application/json; charset=utf-8",
          data: $('#share-form').serialize(),
          success: function(){
            console.log('success');
            console.log( $('#share-form').serialize());
          }, error: function(xhr, textStatus, errorThrown) {
            alert(xhr.responseText);
            console.log( $('#share-form').serialize());
          }});
        })
        //return false;
      });
</script>

在视图中,当我尝试打印请求对象,我得到了以下数据。

in the view, when i try to print the request object, I get the following data

print request.data
'title=adsl%3Blsaj%3Blj%3Bl&body=j%3Bas%3Bl%3Bl+&share_id='

但是,如果我尝试做的,

But if I try to do,

print request.form.get('title', 'None')

我得到没有

有人能告诉我如何解决这一问题?

Can somebody tell me how to fix this ?

推荐答案

正在设置内容类型为应用程序/ JSON 但发送应用/ X WWW的形式,urlen codeD 数据代替。

You are setting the content type to application/json but are sending application/x-www-form-urlencoded data instead.

设置正确的内容类型:

$.ajax({
  url: '/share',
  type: 'post',
  contentType: "application/x-www-form-urlencoded",
  data: $('#share-form').serialize(),

或者更好的是,通过完全省略的contentType 键,把它的默认值。

or better still, leave it at the default by omitting the contentType key altogether.

 
精彩推荐
图片推荐