2012-02-08 97 views
2

我很努力地獲取從網頁發送到我的服務器的JSON字符串。jQuery Ajax調用Twitter Finagle服務器

在網頁上,我做到以下幾點:

$.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字符串?我發錯了,還是接錯了?

回答

2

相反的:

$.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); 
     } 

我現在使用:

$.post(url, 
     JSON.stringify(formData), 
     function(msg) { 
     // TODO: Listen for server ok. If this is successfull.... clear the form 
     alert(msg); 
     }, 
     "json");