Home >Web Front-end >JS Tutorial >How to Call Python Functions from JavaScript Using AJAX?

How to Call Python Functions from JavaScript Using AJAX?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-18 22:47:30846browse

How to Call Python Functions from JavaScript Using AJAX?

Calling Python Functions from JavaScript

As you have mentioned, there might be situations where you encounter a need to utilize Python functions within JavaScript code. To facilitate this, you can employ an approach that involves making asynchronous JavaScript and XML (AJAX) requests to a Python script that handles the function execution.

Python Script:

<code class="python">import json
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/pythoncode.py', methods=['POST'])
def python_function():
    text = request.form.get('param')
    import nltk
    processed_text = processParagraph(text)
    return jsonify(processed_text)</code>

JavaScript Code:

<code class="javascript">var tag = document.getElementsByTagName("p")[0];
text = tag.innerHTML;

$.ajax({
    type: "POST",
    url: "~/pythoncode.py",
    data: { param: text},
    success: function(result) {
        // Handle the response from the Python script
        var processedText = result;
    }
});</code>

Explanation:

In this approach, the JavaScript code sends an AJAX request to the Python script, passing the necessary data (in this case, the text to be processed). The Python script then executes the desired function, processes the input, and returns the result in JSON format. The JavaScript code then receives the response and can utilize the processed data as needed.

The above is the detailed content of How to Call Python Functions from JavaScript Using AJAX?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn