I’m trying to understand these codes, but it’s not making sense to me. Can anyone help me? I’m a beginner

Asked

Viewed 74 times

0

The idea is that the Javascript code communicates with the Python code calling a function and providing arguments, but exactly how it works does not understand very well.

Javascript code:

set_wheels (args)
    {
        const dist = Cast.toString(args.DISTANCE);
        $.ajax({
          header: {
              "Access-Control-Allow-Origin": "*",
              "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS"
          },
          url: 'http://'+window.location.hostname+':8080'+'/set_wheels?lw='+dist,
          success: function( response ) {
              log.log(response);
              log.log(dist);
          }
        });
    }

Python code:

from bottle import Bottle,response,request

class Classe(Bottle):
    def set_wheels(self):
            response.headers['Access-Control-Allow-Origin'] = '*'
            response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
            response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'
            response.headers["Set-Cookie"]= 'SameSite=None;Secure'
            rw=request.GET.get('rw', '').strip()
            lw=request.GET.get('lw', '').strip()
            self.rapi.setJointSpeed(right_rotation=float(rw),left_rotation=float(lw))
        #     print("set_wheels")
            return "set_wheels"

1 answer

1


Good night,

I had similar difficulty when I started programming in Java Script.

I don’t program much in Python for this purpose that I’m using. More I can help you understand a little.

Ajax is responsible for making a communication via POST or GET with the backend, and pass data to it. So whenever Ajax runs it "calls" the page through the URL and exchange data note that there is the function Success, which is where the return is if the page is available and the communication has worked. It can still be used beforeSend and error. Beforesend is executed while executing the Ajax request. And if something goes wrong instead of running the Success will execute error. See below.

        const dist = Cast.toString(args.DISTANCE); 
        $.ajax({
          type: 'post',
          header: {
              "Access-Control-Allow-Origin": "*",
              "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS"
          },
          url: "http://url_requisicao",
          data: {"variavel":valor, "variavel2":valor2},
          beforeSend: function () {
            //faça algo aqui enquanto carrega.
        }, 
          success: function( response ) {
              log.log(response);
              log.log(dist);
          },
           error: function (jqXHR, textStatus, errorThrown) {
            alert("Erro. Falha na conexão!");
        }
          
        });

Note that I can pass specific data through the "date:" method. And also choose the POST or GET method.

In the documentation of website official contains more details.

In the Python page that you will point to through the variable "url" in Ajax, you can execute whatever you want. And receive the values sent via Ajax. Behold:

import cgi;
import cgitb
cgitb.enable()

if (form.has_key("variavel") and form.has_key("variavel2")):
    display_data(form["variavel"].value, form["variavel2"].value)
else:
    display_error()

It would be more or less that ai if you want to execute a specific function it would be interesting to receive the value of Ajax in a variable and create a condition to call this function.

Source: https://api.jquery.com/jquery.ajax/ ; https://gist.github.com/twmht/9935260 ; https://docs.python.org/3/library/cgi.html ;

  • Legaal! Interesting, thanks for the answer! I just didn’t understand very well this part of "where to where". So the communication port is done by the url? That is, the two will listen to this url to capture data and so, send each other? From what I understand your code is: will be of the post type, ie, will SEND data; headers do not understand what it is for; url is where the data will be sent; date is the data itself will be sent; sucess is if sent; this log.log does not understand tbm, you know what is?

  • That’s right, the port is placed in the url, for example: "http://myfile:8080";

  • headers: as it says is a header, and passes information to the request page. do not necessarily need to include in the Ajax request, unless it is a case that needs to be passed. If you are going to look at all the pages you access has a header with some information. Just look at the developer part of the browser. log.log() can be replaced by console.log(reply). It will show the return response of the Ajax function, but this is just to see the information on the developing part, do not need to show it. Use only help handle Ajax return code.

  • Hmmm, I think it’s getting clearer anyway. The essential then is the type, date and url then ne? So in this Python code that you did, the way it will RECEIVE the data would be through this form? In the python file does not use Nennhuma url? how will he know where the data comes from?

  • That would be it. To know the origin of the request address on the page just use the following code: import os origin = os.environ.get("REMOTE_HOST")

Browser other questions tagged

You are not signed in. Login or sign up in order to post.