jquery.ajax post请求获得来自应用程序引擎服务器数据应用程序、服务器、引擎、数据

2023-09-11 01:08:04 作者:绊绊绊绊死你

道歉了前面的noob问题...

Apologies up front for the noob question...

您好,我怎么使用jQuery.ajax的应用程序引擎服务器的Python的结束处获取数据?我知道如何将数据用ajax和相应的处理程序发送到服务器,但我想知道如果有人能告诉我什么是Ajax请求从服务器获取值的模样。 (假设我希望得到一个数字数据存储,并使用它的JavaScript)。

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

客户端发送到服务器(使用jQuery)

client sending to server (using jquery)

客户端JavaScript:

client-side javascript:

//jQuery and ajax function loaded.

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

服务器端:

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

和下高清的main():,我有处理程序('/ put_in_datastore,ResultsHandler)

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

此外,这将是类似code可以从Python的结束检索数字?如果有人能够同时提供处理器code和JavaScript的code,这将是巨大的......

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

推荐答案

的机制是完全一样的任何一种方式中的数据流。在使用Ajax调用的成功参数来对数据进行操作的要求成功完成之后。这通常被称为回调。其他的回调存在。请参见 http://api.jquery.com/jQuery.ajax/ 的完整信息。

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
  }
});

在Python的结束,返回的数据与 self.response.write.out(输出)。参见下面的例子。

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)

此外,你的URL路由应该像('/ resultshandler,ResultsHandler)。我不知道在哪里 / put_in_datastore 是从哪里来的。

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

最后,注意 DEF发布,而不是 DEF获得,因为我正在做一个使用JavaScript POST 请求。你可以做一样的 GET 的要求,在这种情况下,你会使用 DEF获得

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.