Skip to main content
 首页 » 编程设计

javascript之将 JSON 从 JavaScript 返回到 Python

2025年05月04日28thcjp

我正在编写一个简单的 App Engine 应用。

我有一个简单的页面,允许用户在 Google map 实例上移动标记。每次用户放下标记时,我都想将经度/纬度返回到我的 Python 应用程序。

function initialize() { 
 
  ... // Init map 
 
  var marker = new GMarker(center, {draggable: true}); 
  GEvent.addListener(marker, "dragend", function() { 
    // I want to return the marker.x/y to my app when this function is called .. 
  }); 
 
} 

据我(诚然有限)的知识,我应该:

1).在上面的监听器回调中返回包含我所需数据的 JSON 结构

2).在我的 webapp.RequestHandler 处理程序类中,尝试在 post 方法期间检索 JSON 结构。

我非常希望将此 JSOn 数据传递回应用程序而不会导致页面重新加载(这是迄今为止我使用各种 post/form.submit 方法时发生的情况)。

任何人都可以向我提供一些伪代码或示例,说明我如何实现我所追求的目标吗?

谢谢。

请您参考如下方法:

防止页面重新加载的方法是在网页端使用 AJAX 处理。

使用 jquery,你可以做这样的事情:

$("#testform").submit(function() { 
    // post the form values via AJAX... 
    var postdata = {lat: $("#lat").val(), long: $("#long").val()} ; 
    $.post('/submit', postdata, function(data) { 
        // and set the location with the result 
        $("#location").html(data['location']) ; 
       }); 
    return false ; 
    }); 

假设您有这样一个网页:

<p>Enter lat and long:</p> 
<form id="testform" action="#" method="post"> 
    <p> 
    <label for="lat">Lat:</label> 
    <input type="text" id="lat" /> <br /> 
    <label for="long">Long:</label> 
    <input type="text" id="long" /> <br /> 
 
    <input type="submit" value="Get Location" /> 
    </p> 
</form> 
 
<p>The location is:</p><p id="location">(enter lat and long above)</p> 

然后让 python 代码返回 JSON 字典中的位置。

最后,我建议有一个优雅的回退:如果用户禁用了 JavaScript,请定期发帖至/getlocation 并重新加载,然后让 JavaScript 覆盖它以提交到返回 json 的特殊 URL,例如 /getlocationajax