jquery.ajax post request to get data from app engi

2019-05-21 02:58发布

Apologies up front for the noob question...

Hello, how do I get data from the Python end of an appengine server using jQuery.ajax? I know how to send data to the server using ajax and an appropriate handler, but I was wondering if someone could tell me what the ajax request for getting values from the server looks like. (Suppose I wanted to get a number from the datastore and use it in the javascript).

client sending to server (using jquery)

client-side javascript:

//jQuery and ajax function loaded.

<script type="text/javascript">
    var data = {"salary":500};
    $.ajax({
    type: "POST",
    url: "/resultshandler",
    data: data
</script>

server-side:

class ResultsHandler(webapp.RequestHandler):
    def get(self):
        n = cgi.escape(self.request.get('salary'))
        e = Engineer(salary = n)
        e.put()

and under def main():, I have the handler ('/put_in_datastore', ResultsHandler)

Again, what would be the similar code for retrieving numbers from the Python end? If someone could provide both the handler code and javascript code that would be great...

1条回答
smile是对你的礼貌
2楼-- · 2019-05-21 03:12

The mechanism is exactly the same either way the data is flowing. Use the success parameter on the ajax call to operate on the data after the request successfully finishes. This is generally called a callback. Other callbacks exist. See http://api.jquery.com/jQuery.ajax/ for the complete information.

$.ajax({
  url: "/resultshandler",
  type: 'POST',
  data: data,
  success: function(data, status){
    //check status
    //do something with data
  }
});

On the Python end, you return data with self.response.write.out(output). See example below.

class ResultsHandler(webapp.RequestHandler):
    def post(self):
        k = db.Key.from_path('Engineer', the_engineer_id) #will be an integer
        e = db.get(k)
        output = {'salary': e.salary}
        output = json.dumps(output) #json encoding
        self.response.write.out(output)

Also, your url routing should look like ('/resultshandler', ResultsHandler). I don't know where /put_in_datastore came from.

Finally, notice the def post rather than def get because I'm making a POST request with the Javascript. You could do the same as a GET request, and in that case you'd use def get.

查看更多
登录 后发表回答