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!