简体   繁体   中英

Javascript/Python - click a button on a website and run a function in python

It is currently 2:17PM and I have been working on this since 8AM. I usually do python. I want to make a array of buttons where clicking a button will run a python function on the server. I want to do this by sending a web request from the client javascript to a python server, which will receive it, parse it, and run the correct function. I have tried webhooks, websockets, ajax, and manually parsing GET and POST requests. I can't get it to work, there seems to be nothing online about webhooks in python, python websocket API's insist you use async and don't even work, I barely understand ajax but it doesn't let you change ports, and when I try to manually parse requests all I get is the initial connection and clicking the button won't send any more.

This is my latest attempt client side, get request parsing (I wanted to change ports or parse the headers but I only get data when the sockets in python first create the connection, I get nothing later when I click the button.)

<html>
<head>
<title>Dashboard v0.1</title>
<script>
    function send(theUrl)
    {
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open( "GET", theUrl, false);
        xmlHttp.send(null);
        return xmlHttp.responseText;
    }
</script>

<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>

</head>
<body>
    <button type="button" onclick="send("http://127.0.0.1:34000")">Test</button>
</body>
</html>

This is my latest attempt server side:

from threading import *
from socket import *

server = socket(AF_INET, SOCK_STREAM)
Port = 34000

Host = ""
BufferSize = 2048
server.bind((Host, Port))
server.listen(1000)

while True:
    connection, address = server.accept()
    print("Accepted connection")

    while True:
        response = connection.recv(BufferSize).decode("utf8")
        print(str(response))

Please help. I just want to send a request. I frankly don't give a shit about security, it's on my home network. I don't know javascript, this is all code snippets.

I found the answer! Simply reply with HTTP/1.1 200 OK to shut the browser up. Here's my implementation:

def listen(id, server):
    while True:
        client_connection, client_address = server.accept()
        request_data = client_connection.recv(1024)
        executeCommand(id)

        http_response = b"""\
    HTTP/1.1 200 OK
    """
        client_connection.sendall(http_response)
        client_connection.close()

        print(str(id))```

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