[英]Passing variables from python to javascript
我正在使用Google App Engine制作網頁。 它涉及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']
因此,我需要將python代碼中的“經緯度”和“經度”發送到javascript,以便經緯度為RESULT-A和經度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類的標題中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.