Python, Flask: TypeError: 'NoneType' object has no attribute '__getitem__' for filled form

Python, Flask: TypeError: 'NoneType' object has no attribute '__getitem__' for filled form

我查看了以前涉及相同错误的问题,但未能找到解决我的问题的有效方法。我的 html 代码中有一个表单(作为单页应用程序的一部分),我希望通过 ajax.

提交到我的 python 服务器

details.html中的表格:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>A Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">`  
<link href= {{ url_for("static",filename="css/bootstrap.min.css") }} rel="stylesheet" media="screen">
</head>
<body>

<div>
<form method="post"> 
    <label for="address">Address</label>
    <input class="form-control" type="text" name="address">

    <label for="postalcode">Postal Code</label>
    <input class="form-control" type="text" name="postalcode"><br>

    <label for="city">City</label>
    <input class="form-control" type="text" name="city">

    <label for="country">Country</label>
    <input class="form-control" type="text" id="country_indicator" placeholder="Country" name="country"> 

    <button id="submitForm" type="submit">Submit</button>

</form>
</div>

<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src={{ url_for("static", filename="js/bootstrap.min.js") }}></script>
<script src={{ url_for("static", filename="js/details.js") }}></script>
</body>
</html>

如果我从 html 表单中删除 'method="post"',页面会清空表单并重新加载,但即使表单已完全填写,我也会收到上述错误。我的猜测是表单和 JS 之间的某些东西不起作用,因为 request.json 总是 returns NoneType 对象。

details.js:

$(document).ready(function() {

$("#submitForm").click(function(){

    var address = $("#address").val();
    var postalcode = $("#postalcode").val();
    var city = $("#city").val();
    var country = $("#country").val();
    console.log(address);

    var details = {
        "address" : address,
        "postalcode" : postalcode,
        "city" : city,
        "country" : country
    }
    console.log(details.city);

    $.ajax({
        type: "POST",
        url: "/details",
        data: JSON.stringify(details, null, '\t'),
        contentType: 'application/json;charset=UTF-8',
        success: function(result) {
            console.log(result)
        }
    })
    })
})

注意:我添加了 console.log 用于故障排除,但是 js-console 中没有出现文本,这就是为什么我认为问题已经出现在这一点之前。

我的 .py 文件中的相关 app.route:我还没有使用 details.js 中的值,我只是希望看到确实发送了一些东西。这就是为什么我现在只 return "ok"。

@app.route('/details', methods=['GET', 'POST'])
def details():
  if request.method == "POST":
    print(request.json['address']) # . TypeError: 'NoneType' object has no attribute '__getitem__' - crash appears here.
    return "ok")
return render_template("details.html")

因此,由于前面步骤中的一些问题,我假设发送到 .py 文件的对象是 NoneType。我对 python 和 JS 很陌生,所以任何指点都将不胜感激。先感谢您!

编辑:我现在也遇到了 "uncaught ReferenceError: $ is not defined" 来自 javascript 控制台,但是将 jquery- 移到头部解决了那个问题

呸!数据未正确发送到服务器!我在下面重写了您的一些代码。我希望你不介意,但表单现在将使用普通 post 变量而不是 JSON.

提交
@app.route('/details', methods=['GET', 'POST'])
def details():
    # This is our new method, notice it's a bit streamlined.

    if request.method == "POST":
        # We can get the post data using request.form.get(). The first variable is the name="" attribute in HTML, and the second is the default value if it wasn't found in the data.
        return "The address was %s" % request.form.get('address', 'not provided! :O')
    return render_template("base.html")

现在 Javascript!

$(document).ready(function() {
$("#submitForm").click(function(e){

    // Prevent the HTML page from submitting the form since we're doing this by AJAX. This would cause duplications and other issues.
    e.preventDefault();

    // Get a FormData object from the page
    var data = new FormData($('form')[0]);

    // You don't HAVE to send your data by JSON, and in this instance it will be easier not to
    $.ajax({
        type: "POST",
        url: "/details",
        data: data,
        processData: false,
        contentType: false,
        success: function(result) {
            console.log(result)
        }
    })
    })
})

希望对您有所帮助!如果这为您解决了问题,请不要忘记将答案标记为已解决。 :)