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

如何通过Python函数get_maps()创建JavaScript变量?调用代码报错‘list is not a function’

Fixing the "list is not a function" Error & Calling Python Functions from JavaScript

Let's break down what's going wrong here and fix it step by step:

Core Issue: Mixing Server-Side and Client-Side Code

Python runs on your server, while JavaScript runs in the user's browser—they’re completely separate environments. Your current code tries to call get_maps() (a Python function) directly in the AJAX done callback, but this function doesn’t exist in JavaScript. That’s the root cause of your error (the "list is not a function" message likely stems from misassigning values before the AJAX request completes, but the bigger problem is the cross-environment function call attempt).


Step 1: Update Your Python Script to Handle AJAX Requests

Your mapsinterpeter.py needs to accept POST parameters from the frontend, run your get_maps() function, and return the result as JSON (so JavaScript can parse it easily). Here’s a basic example using Flask (adjust for your server framework if needed):

from flask import Flask, request, jsonify

app = Flask(__name__)

def get_maps(year, category):
    # Your existing function logic here
    # Example return (replace with your actual data):
    return {"map_data": [f"Entry 1 for {year} - {category}", "Entry 2", "Entry 3"]}

@app.route('/mapsinterpeter', methods=['POST'])
def handle_map_request():
    # Grab parameters sent from the frontend
    year = request.form.get('year')
    category = request.form.get('category')
    
    # Execute your function
    result = get_maps(year, category)
    
    # Send back the result as JSON
    return jsonify(result)

if __name__ == '__main__':
    app.run(debug=True)

Step 2: Fix the Frontend JavaScript Code

Your AJAX call needs to send the year and category parameters to the server, then use the server’s response instead of trying to call the Python function directly. Also, remember AJAX is asynchronous—you can’t access the result outside the done callback, since the request won’t have finished yet.

Here’s the corrected JS code:

onSubmit(e) {
    e.preventDefault()
    const yearInput = year; // Assuming these are your DOM input elements
    const catInput = cat;
    const msgElement = msg;

    if (yearInput.value === "" || catInput.value === "") {
        msgElement.textContent = "Please fill out the fields"
        msgElement.classList.add("error");
    } else {
        msgElement.textContent = ""
        msgElement.classList.remove("error");
        
        $.ajax({
            type: "POST",
            url: "/mapsinterpeter", // Use your actual server endpoint (remove ~ if not needed)
            data: {
                year: yearInput.value,
                category: catInput.value // Send parameters to the server
            }
        }).done(function(serverResponse) {
            // Use the JSON data returned from your Python function
            const list = serverResponse.map_data; // Match the key from your Python return
            console.log(list); // Log the result here (inside the callback!)
            // Add logic here to render the list data on your page
        }).fail(function(error) {
            // Handle request errors (e.g., server downtime, invalid inputs)
            msgElement.textContent = "Failed to fetch map data. Please try again."
            msgElement.classList.add("error");
            console.error("AJAX Error:", error);
        });
        
        yearInput.value = ""
        catInput.value = ""
    }
}

Key Fixes Explained:

  • Pass Parameters in AJAX: Added a data property to send the user’s input values to the server.
  • Use Server Response: Instead of calling get_maps() in JS, we use the serverResponse returned by the Python script.
  • Asynchronous Safety: All code that uses the result lives inside the done callback—your original console.log(list) would run before the AJAX request finished.
  • Error Handling: Added a fail callback to catch and report issues with the request.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 19:42:34