【问题标题】:Why AJAX is showing me a JSON file which I have returned through view function in flask?为什么 AJAX 向我显示我通过烧瓶中的视图函数返回的 JSON 文件?
【发布时间】:2020-08-01 11:15:00
【问题描述】:

我使用烧瓶作为后端,我有一个按钮,使用 AJAX,我在烧瓶中调用一个视图函数。我创建了一个子文件来存储一些表单数据。

当我填写表单并按下按钮时,我的函数上传会被调用,它会创建结果并将其推送到 JSON 文件。 我正在返回这个 JSON 文件,以便我可以将它动态地显示到前端。 但我得到的是整个 JSON 文件,而不是数据。

上传视图调用 api/test 生成消息并将该消息添加到 data.json 文件中

我在其他项目中使用过 ajax 和类似功能,但从未出现此错误。

这是我的表单和 ajax 代码。

    $(document).ready(function () {
            $('#upload').on('click', 'button', function () {
       
            let photos_fd = new FormData()
            var img = document.getElementById('photos').files.length;
            if (img == 0) {
                $('#msg').html('<span style="color:red">Select at least one file</span>');
                return;
            }
            console.log(document.getElementById('photos').files[0])

            for (var x = 0; x < img; x++) {
                photos_fd.append("photos[]", document.getElementById('photos').files[x]);
            }
            
            let formData = new FormData()
                formData.append("email", $('#email').val());
                formData.append("label", $('#label').val());

                console.log("you submit the form", $('#email').val(), $('#label').val() );

                $.ajax({
                    url: " {{url_for('upload')}} ",
                    dataType: 'json',
                    cache: false,
                    async: true,
                    contentType: false,
                    processData: false,
                    data: formData,
                    photos : photos_fd,
                    type: '',
                    success: function(data) {
                        console.log("xxxxxxx");
                        alert(data.keys());
                        // console.log("",response);
                    },
                    error: function(response) {
                        $("#msg").text(response.response); // display error response
                    }
                });
            });
        });    
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="contact-clean">
        <form method="post" action="{{ url_for('upload') }}" enctype="multipart/form-data">
            <h2 class="text-center">Upload Image</h2>
            <div class="form-group">
                <input class="form-control is-invalid" type="email"  id='email' name="email" placeholder="Email">
            </div>
            <div class="form-group">
                <input class="form-control" type="text" id="label" name="label" placeholder="Image Name">
            </div>
           
            <div class="form-group">
                <input type="file" id="photos" name="photos[]">
            </div>
            <div class="form-group">
                <button id ="upload" class="btn btn-primary" type="submit">UPLOAD</button>
            </div>
        </form>
    </div>

烧瓶视图 上传

@app.route('/', methods=['POST'])
def upload():
  if 'photos[]' in request.files:
  photos = request.files.getlist('photos[]')
  photo = photos[0]

  label = request.form["label"]
  email = request.form["email"]

  img_formate = "." + str(photo.filename).split(".")[-1] 

  image = label + img_formate
  photo.save(os.path.join(app.config['UPLOAD_FOLDER'], image))

  result = {
     label:
     {
        'image': image,
        'email': email,
        'caption': json.loads(response.text)['message']
     }
  }

  with open('templates/data.json') as f:
     data = json.load(f)

  data.update(result)

  with open('templates/data.json', 'w') as f:
     json.dump(data, f,indent=4)

  if photo.filename != '':
     return data

其他: 返回重定向(url_for('index'))

单击按钮时,我得到了这样的 JSON 文件。 我希望返回的 JSON 对象被打印到表单下方的屏幕上,但是,返回的数据直接打印到浏览器窗口,它不维护“index.html”的结构(它有导航栏和表单)。我被退回了这个::

{
    "img1": 
    {
    "caption": " a man holding a dog in a white shirt ", 
    "email": "m@gmail.com", 
    "image": "img1.jpg"
    }
}

【问题讨论】:

    标签: javascript python json ajax flask


    【解决方案1】:

    在这里分析您的代码后,我发现了错误: 1.在脚本的第二行,应该是#form而不是#Upload 2.你在Ajax Call中没有提到type

    以下是修改后的 javascript 代码

    $(document).ready(function () {
                $('#form').on('submit', function (e) {
                e.preventDefault();
                let photos_fd = new FormData()
                var img = document.getElementById('photos').files.length;
                if (img == 0) {
                    $('#msg').html('<span style="color:red">Select at least one file</span>');
                    return;
                }
                console.log(document.getElementById('photos').files[0])
    
                for (var x = 0; x < img; x++) {
                    photos_fd.append("photos[]", document.getElementById('photos').files[x]);
                }
                
                let formData = new FormData()
                    formData.append("email", $('#email').val());
                    formData.append("label", $('#label').val());
    
                    console.log("you submit the form", $('#email').val(), $('#label').val() );
    
                    $.ajax({
                        url: " {{url_for('upload')}} ",
                        dataType: 'json',
                        cache: false,
                        async: true,
                        contentType: false,
                        processData: false,
                        data: formData,
                        photos : photos_fd,
                        type: 'POST', 
                        success: function(data) {
                            console.log("xxxxxxx");
                            alert(data.keys());
                            // console.log("",response);
                        },
                        error: function(response) {
                            $("#msg").text(response.response); // display error response
                        }
                    });
                });
            }); 

    【讨论】:

    • 感谢@imrankhan 帮助我。谢谢。
    猜你喜欢
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-22
    • 2017-08-24
    • 1970-01-01
    相关资源
    最近更新 更多