简体   繁体   中英

What format is a jQuery ajax post request sending the data in and how can it be accessed through Flask's request object?

I am creating a web page that sends an XHR AJAX request using jQuery's $.post() object. The post is being received by a Flask app that is on another domain. The Javascript is below:

$.post('http://myurl.com/create', {
     'title': sender.title,
      'url': sender.url
});

The applicable Flask router code is:

@app.route('/create', methods=['GET', 'POST'])
@crossdomain(origin='*')
def create():
    print(request.args.get('title'))
    if request.method == 'POST':
        title = request.form['title']
        url = request.form['url']

        new_mark = Mark(
            title=title,
            url=url
        )
        new_mark.save()

        return redirect(url_for('index'))

The Python is working great when a form is submitted to the url, but not when I POST through jQuery's AJAX object. It throws a 400 error every time I try to make the AJAX request. I looked at Flask's request.args object, but that has nothing in it when the request is made.

Any ideas?

The problem is that your Ajax request is not configured to target cross domain requests. I suggest the use of $.ajax instead of $.post for more flexibility and to set crossDomain: true in your request configuration.

$.ajax({
  type: 'POST',
  url: 'http://myurl.com/create',
  crossDomain: true,
  data: '{'title': sender.title, 'url': sender.url}',
  dataType: 'jsonp',
  success: function(responseData, textStatus, jqXHR) {
    // Success Callback
  },
  error: function (responseData, textStatus, errorThrown) {
    // Error Callback
  }
});

Hope this will help.

I am stupid. I was not actually sending any data because sender.url and sender.title did not contain any values -_-.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM