3

我正在使用带有 scala 的 Play framework 2.1.1。我查询一个数据库表作为列表返回到控制器,然后将列表转换为字符串并从 javascript 代码返回到 ajax 调用。

如何将查询结果作为json返回并通过控制器返回ajax调用?

应用程序.scala

import play.api._
import play.api.mvc._
import play.api.data._
import views.html._
import models._


object Application extends Controller {

  def index = Action {
    Ok(views.html.index())
  }

  def getSummaryTable = Action{
    var sum="Summary Table";
    Ok(ajax_result.render((Timesheet.getAll).mkString("\n")))
  }

  def javascriptRoutes = Action {  implicit request =>
    import routes.javascript._
    Ok(
    Routes.javascriptRouter("jsRoutes")(
          // Routes
          controllers.routes.javascript.Application.getSummaryTable

    )
    ).as("text/javascript")
  }  
}

时间表.scala

// Use PostgresDriver to connect to a Postgres database
import scala.slick.driver.PostgresDriver.simple._

import scala.slick.lifted.{MappedTypeMapper,BaseTypeMapper,TypeMapperDelegate}
import scala.slick.driver.BasicProfile
import scala.slick.session.{PositionedParameters,PositionedResult}
// Use the implicit threadLocalSession
import Database.threadLocalSession
import java.sql.Date
import java.sql.Time

case class Timesheet(ID: Int, dateVal: String, entryTime: Time, exitTime: Time, someVal: String)

object Timesheet {


 //Definition of Timesheet table
 // object TS extends Table[(Int,String,Time,Time,String)]("timesheet"){
  val TSTable = new Table[Timesheet]("timesheet"){
        def ID = column[Int]("id")
        def dateVal   = column[String]("date")
        def entryTime = column[Time]("entry_time")
        def exitTime  = column[Time]("exit_time")
        def someVal = column[String]("someval")

        def * = ID ~ dateVal ~ entryTime ~ exitTime ~ someVal <> (Timesheet.apply _, Timesheet.unapply _)
   }



  def getAll: Seq[Timesheet] = { 

 Database.forURL("jdbc:postgresql://localhost:5432/my_db", "postgres", "password",null, driver="org.postgresql.Driver") withSession{
  val q = Query(TSTable)
  val qFiltered = q.filter(_.ID === 41 )
  val qDateFilter = qFiltered.filter(_.dateVal === "01/03/2013")
  val qSorted = qDateFilter.sortBy(_.entryTime)

  qSorted.list

  }
 }
}
4

2 回答 2

6

另外,不要忘记为您的模型提供隐式(或不)Json 反序列化器,否则,Scala 编译器会向您大喊大叫:-)。您可以执行以下操作:

def allTimesheet = Action {
  val timesheetWrites = Json.writes[Timesheet] // here it's the deserializer
  val listofTimeSheet = Timesheet.getAll
  Ok( Json.toJson( listofTimeSheet )( timesheetWrites ) )
}

或者您可以使用如下隐式:

def allTimesheet = Action {
  implicit val timesheetWrites = Json.writes[Timesheet] // here it's the deserializer
  val listofTimeSheet = Timesheet.getAll
  Ok( Json.toJson( listofTimeSheet ) )
}

甚至在您的模型伴侣对象中声明您的反序列化器,例如:

伴生对象

object Timesheet {
  implicit val timesheetWrites = Json.writes[Timesheet] // here it's the deserializer
  ....
}

并在控制器中

import models.Timesheet.timesheetWrites

def allTimesheet = Action {
  val listofTimeSheet = Timesheet.getAll
  Ok( Json.toJson( listofTimeSheet ) )
}
于 2013-06-07T10:45:51.217 回答
5

我建议你使用play.api.libs.Json.toJson.

这是一个例子:

object Products extends Controller {
  def list = Action {
  val productCodes = Product.findAll.map(_.ean)
  Ok(Json.toJson(productCodes))
}

Json.toJson返回一个JsValuePlay 将自动为其添加application/json标题的。

请参阅Play For Scala 第 8 章

于 2013-06-07T07:11:41.747 回答