ajax的get-post通信

pvcm50d1  于 2021-07-03  发布在  Java
关注(0)|答案(0)|浏览(126)

首先我知道javascript是客户端。我在java服务器上找不到太多信息,我找到的大部分都运行tomcat或.jsp。我有一个java服务器和一个web客户端。我想用get post建立某种通信。假设我有一个web表单供用户输入他们的名字,然后单击submit,服务器将收到它并显示出来。表单应该由服务器提供还是在客户端提供?客户端如何将数据发送回服务器?
我已将表单放置在服务器中,这样当客户端单击“请求”按钮时,将显示表单并显示一个文本框。我的问题是如何让客户端在web浏览器上输入的消息发送到java服务器?
java服务器

public class JavaHttpServer2 {

  protected void start() {
    ServerSocket s;

    System.out.println("Webserver starting up on port 80");
    try {

      s = new ServerSocket(80);
    } catch (Exception e) {
      System.out.println("Error: " + e);
      return;
    }

    System.out.println("Waiting for connection");
    for (;;) {
      try {

        Socket remote = s.accept();

        System.out.println("Connection, sending data.");
        BufferedReader in = new BufferedReader(new InputStreamReader(
        remote.getInputStream()));
        PrintWriter out = new PrintWriter(remote.getOutputStream());

        String str = ".";
        while (!str.equals(""))
          str = in.readLine();

        out.println("HTTP/1.0 200 OK");
        out.println("Content-Type: text/html");
        out.println("Access-Control-Allow-Origin: *");
        out.println("Server: Bot");
        out.println("");

        out.println("<H1>Test Server</H1>");       
        out.println("<form action=\"home\" method=\"post\">" +
                    "<input type=\"text\" name=\"userName\"><br>" +
                    "<input type=\"submit\" value=\"Login\">" +
                    "</form>");

        out.flush();
        remote.close();
      } catch (Exception e) {
        System.out.println("Error: " + e);
      }
    }
  }

  public static void main(String args[]) {
    JavaHttpServer2 ws2 = new JavaHttpServer2();
    ws2.start();
  }
}

客户

<html>
<body>

<h2>AJAX</h2>

<button type="button" onclick="loadDoc()">Request data</button>

<p id="demo"></p>

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      document.getElementById("demo").innerHTML = xhttp.responseText;
    }
  };
  xhttp.open("GET", "http://127.0.0.1", true);
  xhttp.send();
}
</script>

</body>
</html>

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题