You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask+AJAX调用无结果:alert无法显示文本对比百分比问题

文本对比功能AJAX返回异常问题排查与修复

前端代码问题及修复

  1. 文件获取错误:获取文件元素的属性应为files[0]而非file[0];后续formData.append("FL", FL)中FL未定义,需替换为已获取的file变量。
  2. FormData重复追加:通过new FormData($('#upload_form')[0])已自动获取表单内的JD和FL数据,无需重复append,否则会导致键值重复。
  3. base_url未定义:若未全局定义base_url,直接使用相对路径"/api/Analyze"即可。
  4. JSON结果处理错误:后端返回的是JSON对象,直接alert(result)会显示[object Object],需提取result.result字段。

修正后的前端代码:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  function submitForm() {
    // Show the loading screen
    document.getElementById("loading").style.display = "block";

    // Get the input values
    var JD = document.getElementById("JD").value;
    var file = document.getElementById("FL").files[0]; // 修正files[0]

    // Check if a file has been selected and is a pdf
    if (!file || file.type !== 'application/pdf') {
      alert("Please select a valid PDF file");
      return;
    }

    // Check if file size is less than 5 MB
    if (file.size > 5000000) {
      alert("File size should not exceed 5 MB");
      return;
    }

    // Create a FormData object to send both the file and the jd to the API
    var formData = new FormData($('#upload_form')[0]); // 已包含表单所有数据,无需重复append

    // Make the API call
    $.ajax({
      url: "/api/Analyze", // 直接使用相对路径
      type: "POST",
      data: formData,
      processData: false,
      contentType: false,
      success: function(result) {
        // Hide the loading screen
        document.getElementById("loading").style.display = "none";
        alert(result.result); // 提取JSON中的result字段
      },
      error: function () {
        // Hide the loading screen
        document.getElementById("loading").style.display = "none";
        alert("Error during API call");
      }
    });
  }
</script>
</head>
<body>
  <h2>Analysis</h2>
  <form id="upload_form" enctype="multipart/form-data">
    <p>
      <label for="JD">Description:</label>
      <textarea name = "JD" id="JD" rows="4" cols="50"></textarea>
    </p>
    <p>
      <label for="FL">FILE:</label>
      <input type="file" name="FL" id="FL" accept="application/pdf">
    </p>
    <p>
      <input type="button" value="Submit" onclick="submitForm()">
    </p>
  </form>
  <div id="loading" style="display: none;">Loading...</div>

后端代码问题及修复

  1. 字符串拼接错误:match是浮点数,直接与字符串拼接会报错,需转换为字符串,建议格式化保留两位小数提升可读性。
  2. 除以零风险:当jd_text为空时,len(jd_text.split())为0,会触发除以零错误,需添加判断处理。

修正后的后端代码:

from flask import Flask, render_template, redirect, request, jsonify
import fitz
import re
import sys

app = Flask(__name__)

@app.route('/', methods=['GET'])
def index():
    return render_template('index.html')

@app.route('/Analyze', methods=['GET'])
def analyze():
    return render_template('analyze.html')

@app.route('/BulkAnalyze', methods=['GET'])
def bulk_analyze():
    return render_template('Bulk.html')

@app.route('/api/Analyze', methods=['POST'])
def Submit():
    pdf_file = request.files['FL']
    jd_text = request.form['JD']
    
    jd_text = " ".join(jd_text.split('\n'))

    with fitz.open(pdf_file) as doc:
        text = ''
        for page in doc:
            text += page.get_text()
    text = ' '.join(text.split('\n'))

    # Perform text comparison
    jd_words = jd_text.split()
    if not jd_words:  # 处理空输入情况
        return jsonify({'result': 'The matching percentage is : 0%'})
    
    text_words = text.split()
    matching_words = [word for word in jd_words if word in text_words]
    match = 100 * len(matching_words) / len(jd_words)
    # 格式化保留两位小数并转换为字符串
    return jsonify({'result': f'The matching percentage is : {match:.2f}%' })

if __name__ == "__main__":
    app.run(debug=True) # 开启debug方便排查错误

内容的提问来源于stack exchange,提问作者user21205731

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 15:40:38