简体   繁体   中英

Sending data with XMLHttpRequest

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:

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:

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()

I know nothing about javascripts' XMLHTTPRequest but at some point, you need to send the name to 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

name = request.args.get('name', '')

then you can uppercase() it, and return it in some format - probably XML ?

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:

from flask import Flask, jsonify, request
from flask_cors import CORS
import requests

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM