Location:Home > [Play-Scala-2.2.1] 接收jQuery Post的原始字符串请求

[Play-Scala-2.2.1] 接收jQuery Post的原始字符串请求

 1. 客户端jQuery代码   

 页面上负责发送Post请求的jQuery代码如下:

$.ajax({
  type: "POST",
  url: "/receive",
  data: $("#data").val(),
  contentType: "text/plain", 
  processData: false,
  success: function(res){
    $("#mess").text(res);
  }
});
 这里需要注意的是第5行,将contentType设置为 text/plain,Play会根据contentType解析请求数据,
contentType: "text/plain"


2. 服务端Play代码

 routes文件中配置:
POST /receive controllers.Application.receive
 Action代码:
def receive = Action { request =>
    val content = request.body.asText.get
    Ok("Receive: " + content)
}

  这里需要注意的是获取请求数据的方法调用:request.body.asText,如果Post请求的contentType不是text/plain,则该方法调用将会返回None,进而导致get方法报错。

Related
Your Answer
(Ctrl+Enter To Post)   
    Copyright © 2015-2017 163JAVA.COM All Rights Reserved.