Home > Web Front-end > JS Tutorial > body text

How to Call Python Functions from JavaScript Using AJAX?

Patricia Arquette
Release: 2024-10-18 22:47:30
Original
684 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!