2013-06-04 2 views
0

환경 반환해야합니다 : 스칼라 2.10, 2.1.1 재생, 4.2아약스, 컨트롤러는 JSON을 반환하고 HTML 페이지를

사용 사례 일식 : 사용자의 클릭을 데이터베이스 오브젝트 (게임을) 파악 링크 . ajax 요청은 Javascript Route를 통해 컨트롤러로 보내집니다. 컨트롤러는 게임 데이터를로드하고이를 json으로 변환 한 다음 다시보기로 보냅니다. 아약스 성공 콜백은 게임 타이틀을 div에 인쇄합니다.

문제 : 나는 JSON을 얻을 해달라고하지만, HTML 페이지 (아약스 요청을 보내는 s의있는 페이지).

나는 문제가 라우터에 의심 : 나는 자바 스크립트 경로 행동에 인쇄 ("경로") 및로드 게임 작업에 인쇄 ("로드 게임")를 넣어. "경로"는 콘솔에 표시되지만 "로드 게임"에는 표시되지 않습니다. 그것은 또한 내 loadGame (ID) 경로에서 올 수 있습니다,하지만 내가 어떻게 설정해야 볼 수 없습니다.

여기 내 코드입니다.

경로 :

# Routes 
# This file defines all application routes (Higher priority routes first) 
# ~~~~ 

# Home page 
GET /        controllers.Application.index 

# Javascript routes 
GET  /javascriptRoutes    controllers.Application.javascriptRoutes 

# Library 
GET  /library/:id     controllers.UserController.library(id: Long) 
GET  /library/:id     controllers.GameController.loadGame(id: Long) 

보기 : 자바 스크립트 경로와

<div class="span2"> 
        <ul class="nav nav-pills nav-stacked"> 
         @userGames.map { game => 
          <li><a href="#" onclick="displayGameInfo(@game.id)">@game.title</a></li> 
         } 
        </ul> 
       </div> 
... 
<script> 
      var successFn = function(data) { 
       $('#gameInfo').html(''); 
       $("#gameInfo").append('<h4>'+data.title+'</h4>') 
      } 

      var errorFn = function(err) { 
       console.debug("Error of ajax Call"); 
       console.debug(err); 
      } 

      ajax1 = { 
       dataType: 'text', 
       contentType:'application/json', 
       success: successFn, 
       error: errorFn 
      } 

      var displayGameInfo = function(id) { 
       javascriptRoutes.controllers.GameController.loadGame(id) 
        .ajax(ajax1); 
      } 
     </script> 

와 ApplicationController : ... loadGame (ID) 방법

object Application extends Controller { 
    def javascriptRoutes = Action { implicit request => 
    import routes.javascript._ 
     println("-=== route ===-") 
     Ok(
      Routes.javascriptRouter("javascriptRoutes")(routes.javascript.GameController.loadGame) 
     ).as("text/javascript") 
    } 
} 

GameController :

,
object GameController extends Controller { 
... 
    // Library 
    def loadGame(id: Long) = Action(parse.json) { implicit request => 
    println("-=== load game ===-") 
    val mess = Json.toJson(Game.find(id)) 
    Ok(mess) 
    } 

} 

게임 모델 :

# Library 
GET  /library/:id     controllers.UserController.library(id: Long) 
GET  /library/:id     controllers.GameController.loadGame(id: Long) 

브라우저를 요청 /library/123 URL이, 플레이의 경로를 시도 할 것이다 : 당신의 routes 파일에서

case class Game(id: Long, title: String, description: String, userId: Long) 

object Game { 

    val game = { 
    get[Long]("id") ~ 
    get[String]("title") ~ 
    get[String]("description") ~ 
    get[Long]("userId") map { 
     case id~title~description~userId => Game(id, title, description, userId) 
    } 
    } 

... 

    def find(id: Long): Game = DB.withConnection { implicit c => 
    SQL("select * from game where id = {id}") 
     .on('id -> id).as(game *).head 
    } 


    implicit object GameFormat extends Format[Game] { 

    def reads(json: JsValue) = JsSuccess(Game( 
     (json \ "id").as[Long], 
     (json \ "title").as[String], 
     (json \ "description").as[String], 
     (json \ "uid").as[Long] 
    )) 

    def writes(game: Game) = JsObject(Seq(
     "id" -> JsNumber(game.id), 
     "title" -> JsString(game.title), 
     "description" -> JsString(game.description), 
     "userId" -> JsNumber(game.userId)) 
    ) 
    } 
} 
+0

시도는 자바 스크립트 코드 (예를 들어 크롬을 사용)을 디버깅 할 수 있습니다. 'javascriptRoutes.controllers.GameController.loadGame (id)'행에 도달했는지, 그리고 유효한'id'가 있는지 확인하십시오. – maba

+0

그건 괜찮습니다. 나는 코드와 아약스 요청의 성공 부분에 도달한다. – Gaetz

답변

0

, 같은 URL을 일치하는 경로에 있습니다 선언의 순서는 첫 번째 것과 일치하며 controllers.UserController.library() 액션을 호출합니다. 이것은 아마 당신이 완전한 HMTL 페이지를 얻는 이유 일 것입니다.

시도는 두 번째 경로에 대한 다른 URL을 (하나는 JSON을 반환)를 정의하고 올바른 행동을 일치시킬 수있을 것입니다 재생합니다.

예 :

GET  /library/:id     controllers.UserController.library(id: Long) 
GET  /gameData/:id     controllers.GameController.loadGame(id: Long) 
+0

몇 년 후 답변을 주셔서 감사합니다 :) – Gaetz

관련 문제