将JSON从JavaScript返回到Python

Chr*_*acy 1 javascript python google-app-engine

我正在编写一个简单的App Engine应用程序.

我有一个简单的页面,允许用户在Google地图实例上移动标记.每次用户删除标记时,我都希望将long/lat返回到我的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 ..
  });

}
Run Code Online (Sandbox Code Playgroud)

对于我(公认有限)的知识,我应该是:

1).在上面的侦听器回调中返回带有我所需数据的JSON结构

2).在我的webapp.RequestHandler Handler类中,尝试在post方法期间检索JSON结构.

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

任何人都可以向我提供一些伪代码或一个关于我如何实现我的目标的例子吗?

谢谢.

Rya*_*rom 7

防止页面重新加载的方法是在网页端使用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 ;
    });
Run Code Online (Sandbox Code Playgroud)

假设你有一个这样的网页:

<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>
Run Code Online (Sandbox Code Playgroud)

然后让python代码返回JSON dict中的位置.

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