我正在努力获取从网页发送到我的服务器的 JSON 字符串。
在网页中,我执行以下操作:
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(formData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// TODO: Listen for server ok.
alert(msg);
}
在服务器端,我的 Scala 代码如下所示:
import com.twitter.finagle.Service
import com.twitter.finagle.builder.Server
import com.twitter.finagle.builder.ServerBuilder
import com.twitter.finagle.http._
import com.twitter.util.Future
import java.lang.String
import java.net.InetSocketAddress
import org.jboss.netty.buffer.ChannelBuffers
import org.jboss.netty.util.CharsetUtil.UTF_8
/**
*
*/
object HttpServerExample {
def main(args: Array[String]) {
class EchoService extends Service[Request, Response] {
def apply(request: Request) = {
println(request.getContent());
val response = Response()
response.setContentType(MediaType.Html, UTF_8.name)
val responseContent: String = "Thanks"
response.setContent(ChannelBuffers.copiedBuffer(responseContent, UTF_8))
Future.value(response)
}
}
val echoServer: Server = ServerBuilder()
.codec(RichHttp[Request](Http()))
.bindTo(new InetSocketAddress("127.0.0.1",8080))
.name("EchoServer")
.build(new EchoService())
}
}
由于某种原因,请求内容为空。
如果我将 ajax 调用更改为:
$.ajax({
type: "POST",
url: url,
data: formData,
success: function(msg) {
// TODO: Listen for server ok.
alert(msg);
}
然后我可以将数据作为参数。
如何在服务器上获取 JSON 字符串?我是发错了,还是收错了?