简体   繁体   中英

Flask app with AJAX post gives 404 (NOT FOUND)

I'm new to this and making a small Flask app.

I've gone through everything similar I can find online, but I still can't get a minimal working example of passing data from client-side to server-side using AJAX.

Here is the relevant HTML:

<script type=text/javascript>
$(function() {
  $('a#test_function').bind('click', function() {
    $.ajax({
          url: $SCRIPT_ROOT + '/test',
          data: JSON.stringify({ "value":'asdf' }),
          type: 'POST'
          success: function(response) {
               console.log(response);
          },
          error: function(error) {
               console.log(error);
          }
        });
      });
    });
</script>

<h1>jQuery Example</h1>
<a href=# id=test_function>get string</a>

And here is the .py file:

import os
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash, jsonify, json

# create our little application :)
app = Flask(__name__)

# Load default config and override config from an environment variable
app.config.update(
DATABASE=os.path.join(app.root_path, 'mydb.db'),
DEBUG=True,
SECRET_KEY='something',
SERVER_NAME='http://localhost:5000'
)

@app.route('/')
def welcome():
    flash('Welcome!')
    return render_template('index.html')


@app.route('/test', methods=['GET', 'POST'])
def test():
    vars = request.data
    return ', '.join([str(i) for i in vars])

When I run the server and attempt to run the post request, I get the following error:

 POST http://127.0.0.1:5000/test 404 (NOT FOUND)

Any help greatly appreciated!

To POST JSON data via XHR to Flask the method I use is to set the Content-Type heading to "application/json" . Then you can access this within Flask from the request.data object. I cleaned up a couple typos as well.

Javascript/HTML:

<script type="text/javascript">

    $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};

    $(function() {
        $('a#test_function').bind('click', function() {
            $.ajax({
                type: "POST",
                headers: {"Content-Type": "application/json"},
                url: $SCRIPT_ROOT + "/test",
                data: JSON.stringify({"key": "value"}),
                success: function(response) {
                    console.log(response);
                },
                error: function(response, error) {
                    console.log(response);
                    console.log(error);
                }
            });
        });
    });
</script>

<h1>jQuery Example</h1>
<a href="#" id="test_function">get string</a>

Python:

@app.route('/test', methods=['GET', 'POST'])
def test():
    vars = request.data
    return ', '.join([str(i) for i in vars])

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