在play中实现ajax官方给出jquery实现,我捉摸了一上午终于找到一种利用angular实现的方法。angular是一个js的框架
1、创建一个scala的play工程,修改index.scala.html如下
(message: String) <!DOCTYPE html> <html> <head> <title>ajax</title> <link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/main.css")"> <link rel="shortcut icon" type="image/png" href="@routes.Assets.at("images/favicon.png")"> <script src="http://cdn.bootcss.com/angular.js/1.1.0/angular.min.js" type="text/javascript"></script> <script src="@routes.Assets.at("javascripts/hello.js")" type="text/javascript"></script> </head> <body> <div data-ng-app="myApp"> <script type="text/javascript"> var app = angular.module('myApp', []); </script> <div data-ng-controller="SearchController"> <input data-ng-model="input" data-ng-change="doSearch(input)" autofocus> <h2>There are {{ results.length }} results</h2> hello {{world}} <ul> <li data-ng-repeat="result in results"> {{ result }} </li> </ul> </div> </div> </body> </html>
首先得包含angular.min.js文件,我这里从cdn引用的,data-ng-app是作用域,data-ng-controller="SearchController“ 是控制器,data-ng-model="input"是把输入域的值绑定到应用程序变量 data-ng-change="doSearch(input)"触发doSearch方法, ng-bind 指令把应用程序变量 name 绑定到某个段落的 innerHTML,data-ng-repeat="result in results"实现数组的循环打印
2、在public/javascript下创建hello.js, 内容为
function SearchController($scope, $http) { $scope.results = []; $scope.input = ""; $scope.doSearch = function() { var httpRequest = $http({ method : 'GET', url : "/search/" + $scope.input, }).success(function(data, status) { $scope.results = data; }).error(function(arg) { alert("error "); }); }; // run the search when the page loads. $scope.doSearch(); }3、创建models/Resultpackage models /** * Created by lustre on 2015/8/10. */ import java.io.File case class Result(text: String) // Finds files in the current dir. matching the given search term object Result { // Simple list of files in the current directory def all = new File(".").listFiles().map(file => file.getName()) // Simple case-sensitive filter def find(term: String) = Result.all.filter(_.contains(term)) }其功能是返回包含参数内容的文件列表,即当前目录下的文件列表4、在controler下创建Searchpackage controllers /** * Created by lustre on 2015/8/10. */ import models.Result import play.api._ import play.api.mvc._ import play.api.libs.json._ import play.api.data._ import play.api.data.Forms._ import scala.collection.mutable.ListBuffer import java.io.File object Search extends Controller { // Simple action - return search results as Json def perform(term:String) = Action { val m = Result.find(term) Ok(Json.toJson(m)) } }以json形式传回数据,其中m应该是数组形式5、最后是配置文件GET /search/:term controllers.Search.perform(term:String) GET /search/ controllers.Search.perform(term:String="")然后就可以了,输入框键入a 下面显示包含a的文件名,