英文对照 介绍Play Framework 框架 Ajax

lyuehh 发布于 2010/08/08 13:49
阅读 1K+
收藏 2

Play框架中的Ajax

h1. Ajax in the Play framework

 

Play框架允许你简单的使用Ajax请求,默认使用JQuery,

这一节描述了如何有效地在框架里使用jQuery。

The Play framework allows you to easily perform Ajax requests, and is shipped with "jQuery":http://jquery.com by default.

This section describes how to effectively use "jQuery":http://jquery.com within the framework.

 

Plya也提供了jsAction标签透明的从控制器得到一个定义的方法。

The Play framework also comes with the handy **jsAction** tag to transparently get a method definition from the controller.

 

使用jQuery和jsAction标签

h2. <a>Using jQuery with the jsAction tag</a>

 

jsAction标签返回一个Javascript函数,它基于服务端的action构建了一个URL,没有参数,它不完成Ajax请求,这些需要手动的使用返回的URL完成。

The #{jsAction /} tag returns a JavaScript function which constructs a URL based on a server action and free variables. It does not perform an AJAX request; these have to be done by hand using the returned URL.

 

让我们看个例子。

Let's see an example:

 

bc. GET     /hotels/list        Hotels.list

 

现在你可以在客户端导入这个route

Now you can import this route client side:

 

bc. <script type="text/javascript">

   var listAction = #{jsAction @list(':search', ':size', ':page') /}

   $('#result').load(listAction({search: 'x', size: '10', page: '1'}), function() {

       $('#content').css('visibility', 'visible')

   })

</script>

 

在这个例子中我们从默认的应用控制器中请求list方法,我们传了3个参数,search,size和page,

请求的结果被保存在了listAction变量中,现在我们使用jQuery的load方法发出则个请求(一个HTTP GET请求)。

In this example we are requesting the list method from the default Application controller. We are also passing three parameters: search, size and page. The request we perform is then saved into the listAction variable. Now using jQuery and the **load** function we are performing a request (an HTTP GET request in fact).

 

实际上,发送的是下面的这个请求。

In fact, the following request is sent:

 

bc. GET /hotels/list?search=x&size=10&page=1

 

请求返回的是HTML数据。

In that case the request returns HTML data.

 

但是也可以返回JSON数据或XML数据,然后让JQuery解释这些数据,在你的控制器中,使用恰单的render方法即可。

However, it is also possible to return JSON or XML and to have jQuery interpret the data. In your controller, use the appropriate render method (renderJSON, renderXML or an XML template).

 

请参考jQuery的文档去获得更多的信息。

Please refer to the "jQuery":http://docs.jquery.com/Main_Page documentation for more info.

 

需要注意的是我们还可以使用POST方法,那么相应的jQuery方法应该被改为:

Also please note that we could perform a POST; the jQuery method should then be changed to:

 

bc. $.post(listAction, function(data) {

  $('.result').html(data);

});

 

返回顶部
顶部