AJAX:POST方法内容未传输

时间:2015-07-20 17:24:29

标签: javascript java jquery ajax client-server

我是Client Server应用程序的初学者。在阅读了几个论坛后,我开发了一个带有Java Server的基本Javascript客户端,并尝试使用POST发送数据。但是当我成功建立它们之间的连接时,在我打印接收到的数据时在服务器端,它只打印标题而不是实际的数据内容。喜欢这个

The Client /127.0.0.1:34290 is connected
The HTTP request string is ....
POST / HTTP/1.1
Host: 127.0.0.1:8080
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Content-Length: 30
Origin: null
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

客户端代码是:

$(document).ready(function(){
    $("button").click(function(){
        $.post("demo_test_post.asp",
        {
          name: "Donald Duck",
          city: "Duckburg"
        },
        function(data,status){
            alert("Data: " + data + "\nStatus: " + status);
        });
    });
});

服务器端代码是:

inFromClient = new BufferedReader(new InputStreamReader(connectedClient.getInputStream()));
outToClient = new DataOutputStream(connectedClient.getOutputStream());

String requestString = inFromClient.readLine();
String headerLine = requestString;

StringBuffer responseBuffer = new StringBuffer();
responseBuffer.append("<b> This is the HTTP Server Home Page.... </b><BR>");
responseBuffer.append("The HTTP Client request is ....<BR>");

System.out.println("The HTTP request string is ....");
while (inFromClient.ready()) {
// Read the HTTP complete HTTP Query
    responseBuffer.append(requestString + "<BR>");
    System.out.println(requestString);
    requestString = inFromClient.readLine();
}

有谁能告诉我哪里出错了?

1 个答案:

答案 0 :(得分:0)

您的服务器代码似乎没有打印请求中的最后一行(它通过inFromClient.readLine()读取它,然后inFromClient.ready()切换为false,最后一行被忘记而没有打印。)

试试这个(没有响应的东西,只是为了验证请求是否完整):

inFromClient = new BufferedReader(new InputStreamReader(connectedClient.getInputStream()));

String requestString;
while ((requestString = inFromClient.readLine()) != null) {
    System.out.println(requestString);
}