2016-11-27 98 views
0

我是新手,并制作一个小Flask应用程序。AJAX发布的瓶子应用程序给404(未找到)

我已经经历了类似的事情,我可以在网上找到,但我仍然无法获得使用AJAX从客户端向服务器端传递数据的最小工作示例。

下面是相关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> 

这里是.py文件:

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]) 

当我运行的服务器,并尝试运行POST请求,我得到以下错误:

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

任何帮助非常感谢!

+1

你能后整个'.py'文件? – trendsetter37

回答

1

要通过XHR将JSON数据发布到Flask,我使用的方法是将Content-Type标题设置为"application/json"。然后你可以在Flask中从request.data对象中访问它。我也清理了一些错别字。

的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]) 
+0

嗯...因为我在我的本地环境中引用了一个蓝图(将@ main.route改为@ app.route),所以只做了一个编辑。如果这不能解决问题,请发布完整的HTML 。谢谢! – abigperson

+0

另外 - 这个例子在我的机器上工作,当我点击“获取字符串”链接时,我可以看到一个结果发布到Javascript控制台,Flask的另一个建议是在你的Python中使用大量的打印语句类似于javascript中的console.log),你可以在终端上看到当你在本地运行服务器时的输出 – abigperson

+0

完美的这似乎现在工作,必须是标题,谢谢! – tombird