2010-05-09 3 views
1

간단한 App Engine 앱을 작성하고 있습니다.JSON을 JavaScript에서 Python으로 되 돌리는 방법

사용자가 Google지도 인스턴스에서 마커를 이동할 수있는 간단한 페이지가 있습니다. 사용자가 마커를 떨어 뜨릴 때마다 long/lat를 파이썬 앱에 반환하려고합니다. 내 (틀림없이 제한) 지식으로

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 처리기 클래스에서 게시물 메서드 중에 JSON 구조를 검색하려고합니다.

페이지 재로드를 일으키지 않고이 JSOn 데이터를 앱으로 전달하고 싶습니다. (지금까지 다양한 post/form.submit 메소드를 사용했을 때 일어난 일입니다.)

누구나 내가 뭘했는지 달성 할 수있는 방법에 대한 가짜 코드 나 예제를 제공 할 수 있습니까?

감사합니다.

답변

1

페이지를 업데이트하지 않으려면 XMLHttpRequest를 사용해야합니다. 이 예제에서는 클라이언트 쪽 function Request(function_name, opt_argv)과 서버 쪽 RPCHandler을 사용하고 있습니다. Google App Engine example. 나는이 테스트를하지 않은,하지만 그것은과 같습니다

클라이언트 측 자바 스크립트

function initialize() { 

    ... // Init map 

    var marker = new GMarker(center, {draggable: true}); 
    GEvent.addListener(marker, "dragend", function(position) { 
    Request('update_marker_position', [ unique_identifier, position.lat(), position.lng() ]); 
    }); 

} 

서버 측 파이썬

# Create database model for LatLng position 
class LatLng(db.Model): 
    lat = db.IntegerProperty() 
    lng = db.IntegerProperty() 

... 

class RPCMethods: 
    """ Defines the methods that can be RPCed. 
    NOTE: Do not allow remote callers access to private/protected "_*" methods. 
    """ 

    def update_marker_position(self, *args): 
     # args[0] - unique identifier, say GAE db key 
     # args[1] - lat 
     # args[2] - lng 
     # Note: need to do some checking that lat and lng are valid 

     # Retrieve key and update position 
     position = LatLng.get(db.Key(args[0]) 
     if position: 
      position.lat = args[1] 
      position.lng = args[2] 
     else: 
      position = LatLng(
       lat= args[1], 
       lng= args[2] 
      ) 
     position.put() 

     payload = { 
      'lat': args[1], 
      'lng': args[2], 
     } 
     return payload 

당신이 때 DB를 항목을 만들어야합니다 페이지를 제공하고 db 키 클라이언트 측을 저장합니다. 다른 고유 한 식별자를 사용할 수도 있습니다. 이 경우 전역 변수 'unique_identifier'로 저장했다고 가정했습니다.

또한, ('lat'및 'lng'멤버와 함께) 반환 페이로드를 처리하는 콜백 함수를 추가해야합니다. 이 예제에서, 나는 콜백 함수를 request의 opt_argv 배열에있는 0 번째 매개 변수로 추가한다고 생각한다. 이게 도움이 되길 바란다.

7

페이지를 다시로드하지 못하게하는 방법은 웹 페이지 쪽에서 AJAX로 처리하는 것입니다.

<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> 

다음 파이썬 코드를 가지고 JSON의 위치를 ​​반환 :이 같은 웹 페이지 뭔가를 가정

$("#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 ; 
    }); 

: jQuery를 사용하여

, 당신은 같은 것을 할 수 dict.

마지막으로 나는 우아한 후퇴를 권장합니다. 사용자가 자바 스크립트를 사용 중지 한 경우 예를 들어 /getlocation 및 다시로드 한 다음 JavaScript에서 json을 반환하는 특수 URL (예 : /getlocationajax)으로 바꿉니다.

관련 문제