简体   繁体   English

JSON 发布请求显示 200 成功,但脚本未执行

[英]JSON Post request is showing 200 success, but script is not executing

FrontEnd this gets the name, age, city puts it in a JSON format and sends it to localhost:5100/getJson which is my backend.前端获取名称、年龄、城市,将其以 JSON 格式发送到我的后端 localhost:5100/getJson。

<form>
        <div class="form-group">
            <label for="text">Name:</label>
            <input type="text" class="form-control" id="name" placeholder="Enter name" name="name">
        </div>
        <div class="form-group">
            <label for="text">Age:</label>
            <input type="text" class="form-control" id="age" placeholder="Age" name="age">
        </div>
        <div class="form-group">
            <label for="text">City:</label>
            <input type="text" class="form-control" id="city" placeholder="Enter city" name="city">
        </div>
        <button onclick = "MyFunction()" id = "submitButton" type="submit" class="btn btn-default">Submit</button>
        <p id = "demo">

        </p>
        <script>

            function MyFunction() {
                var name = document.getElementById("name").value
                var age = document.getElementById("age").value
                var city = document.getElementById("city").value
                jsonRequest = {"name":name, "age":age, "city":city}

                fetch('http://localhost:5100/acceptJson', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: jsonRequest
                }).then(res => res.json())

            }
        </script>

my backend is a flask server in python.我的后端是 python 中的 flask 服务器。

Backend后端

app = Flask(__name__)


@app.route('/acceptJson',methods=['GET', 'POST'])
def acceptJson():
    jsonData = request.json
    name = jsonData['name']
    age = jsonData['age']
    city = jsonData['city']
    postToDatabase(name,age,city)
    return "Succesful"

if __name__ == '__main__':
    app.run(host = "localhost", port = 5100)

Now when I make the same JSON post request using software like Postman it works, returns 200 and runs the script.现在,当我使用 Postman 之类的软件发出相同的 JSON 发布请求时,它可以工作,返回 200 并运行脚本。

邮递员工作形象

but when I do it through the code, it return 200 and doesn't run the script, so it's clearly something wrong with the POST in the javascript, but I do not understand where it's wrong.但是当我通过代码执行时,它返回200并且不运行脚本,因此javascript中的POST显然有问题,但我不明白哪里错了。

The problem seems to be related to your front-end.问题似乎与您的前端有关。 In the following answer, I assume your form is submitted by "MyFunction".在以下答案中,我假设您的表单是由“MyFunction”提交的。

In this line of HTML:在 HTML 这一行中:

<button onclick = "MyFunction()" id = "submitButton" type="submit" class="btn btn-default">Submit</button>

The button is a submit type button.该按钮是一个提交类型的按钮。 When you click the button, the browser submits the form as usual.当您单击该按钮时,浏览器将照常提交表单。 With no "action" attribute in the tag, the request is submitted to the webpage you open ie no request was sent to the back-end.标签中没有“action”属性,请求被提交到您打开的网页,即没有请求被发送到后端。

The solution can be found in this question: Form not submitting with JS .可以在这个问题中找到解决方案: Form not submit with JS However, I would suggest another method to do so.但是,我会建议另一种方法来做到这一点。

You may add "event.preventDefault();"您可以添加“event.preventDefault();” before you call the function of handling the request or add it to the beginning of the function to stop the form from being submitted automatically in a traditional way.在调用处理请求的 function 之前或将其添加到 function 的开头以阻止表单以传统方式自动提交。

<button onclick = "event.preventDefault();MyFunction()" id = "submitButton" type="submit" class="btn btn-default">Submit</button>

The reason why to use preventDefault is that it only stop the browser default behavior while other solution (return false) stop the event propagating the DOM.使用 preventDefault 的原因是它只停止浏览器默认行为,而其他解决方案(返回 false)停止传播 DOM 的事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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