将变量从python传递到javascript

Passing variables from python to javascript

本文关键字:javascript python 变量      更新时间:2023-09-26

我正在使用谷歌应用引擎开发网页。它涉及html、python、javascript和Ajax。

工作流程如下:

当有人在html框中引入一个值时,它会调用一个javascript函数:

 INPUT type="text" id="busca" name="busca" onblur="SacarMapa()"

这将调用此函数:

  function SacarMapa()
  {
  var lugar=document.getElementById("busca").value;
    $.ajax("/mapa",
    { "type": "get",
        "data": {busca:lugar},
        // usualmente post o get
        "success": function(result) {
            initMap(RESULT-A, RESULT-B);
            },
        "error": function(result) {
            console.error("Se ha producido un error: ", result);},
        "async": true,})};

我需要的是RESULT-A和RESULT-B。这将来自使用python的服务器端:

class MapHandler(SessionModule.BaseSessionHandler):
   def get(self):
      #Obtencion de datos
      serviceurl = 'http://maps.googleapis.com/maps/api/geocode/json?'
      address=self.request.get('busca')
      self.response.out.write("Busca es "+address)
      url = serviceurl + urllib.urlencode({'address': address})
      uh = urllib.urlopen(url)
      data = uh.read()
      js = json.loads(str(data))
      resultado = js['status']
     if not resultado == "ZERO_RESULTS":
        location = js['results'][0]['formatted_address']
        latitud = js['results'][0]['geometry']['location']['lat']
        longitud = js['results'][0]['geometry']['location']['lng']

因此,我需要将"latitud"answers"longitud"从python代码发送到javascript,这样latitud将是RESULT-A和longitud RESULT-B

做这件事的方法是什么?

谢谢。

已解决:

我终于这样做了:

(Python/服务器端)

class MapHandler(webapp2.RequestHandler):
def get(self):
    #Obtencion de datos
    serviceurl = 'http://maps.googleapis.com/maps/api/geocode/json?'
    address=self.request.get('busca')
    url = serviceurl + urllib.urlencode({'address': address})
    uh = urllib.urlopen(url)
    data = uh.read()
    js = json.loads(str(data))
    try:
            location = js['results'][0]['formatted_address']
            latitud = js['results'][0]['geometry']['location']['lat']
            longitud = js['results'][0]['geometry']['location']['lng']
            self.response.headers['Content-Type'] = 'application/json'
            self.response.out.write (json.dumps({"exito": 1, "lat": latitud, "long": longitud}))
    except Exception as e:
            self.response.out.write (json.dumps({"exito":0}))

Javascript:

function SacarMapa()
{
var lugar=document.getElementById("busca").value;
alert("Buscaremos "+lugar);
debugger;
$.ajax("/mapa",
    { "type": "get",
        "data": {busca:lugar},
        "dataType": "json",
        "success": function(datos) {
            if (datos['exito'] == "1")
            {
                initMap(datos['lat'], datos['long']);
            }
        },
        "error": function(datos) {
            debugger;
            console.error("Se ha producido un error: ", datos);},
        "async": true,})};

我对此非常疯狂,因为我忘记了将webapp2.RequestHandler放在python类的头中。