Sending data with XMLHttpRequest

Lana

New Member
#1
I have a website that should send a name to a python script (on a third-party website) when a button is pressed. This python script will then make the name uppercase and return it back to the website.

Right now an XMLHttpRequest is correctly being sent when the button is pressed, but I'm unsure how I correctly send the data with the XMLHttpRequest, and then how this data is accessed in the python script.

XMLHttpRequest:
Mã:
document.getElementById("myButton").addEventListener("click",
    function() {
        var myRequest = new XMLHttpRequest();

        myRequest.open('GET', 'https://example.com/');

        myRequest.onreadystatechange = function () {
            if (myRequest.readyState === 4) {
                alert(myRequest.responseText);
            }
        }
        myRequest.send("Bob"});
    }
);
Python script:
Mã:
from flask import Flask, jsonify
from flask_cors import CORS
from requests import request

app = Flask(__name__)
CORS(app)

@app.route("/", methods=["GET"])
def hello_world():
    return jsonify(name = (name_sent_by_XMLHttpRequest).upper()) # Should return "BOB"

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

Admin

Administrator
Thành viên BQT
#2
I know nothing about javascripts' XMLHTTPRequest but at some point, you need to send the nameto the python server, right? HOW to do that is up to you, but a GET based option:

GET request with args: https://example.com/?name=your_name_goes_here

in your flask app, the function listening on route "/" will now have access to that arg, something like

Mã:
name = request.args.get('name', '')
then you can uppercase() it, and return it in some format - probably XML ?

Mã:
return Response(my_xml, mimetype='text/xml')
Update based on your comment: usually in a flask function, you would use the flask request object to get your URL parameters. In your example, you're importing the requests module as request, not using it, but clobbering the flask.request namesspace. Change your imports to something like this, and it should work normally:

Mã:
from flask import Flask, jsonify, request
from flask_cors import CORS
import requests
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top