使用Ajax从服务器读取响应

时间:2014-12-29 07:58:57

标签: java ajax

我正在做机器人控制项目,它将Get请求“http //:10.0.1.1/forward”命令发送到机器人中的java服务器,服务器响应“HTTP / 1.1 200 OK \ r \ n \ r \ n \ nOK \ r \ n“表示服务器收到了请求。我的问题是如何从ajax中的服务器读取响应(“HTTP / 1.1 200 OK \ r \ n \ r \ n \ nNOK \ r \ n”)

以下是我在xampp中托管的index.html

var xmlhttp;

if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
    }
else {
    // code for IE6, IE5
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

var page = 'http://10.0.1.1/forward;
xmlhttp.open('GET', page, true); 
xmlhttp.send(null); 

以下是java服务器:

        ss = new ServerSocket(PORT);
        sock = ss.accept();
        System.out.println("server ");
        //get stream to send and receive data
        InputStream is = sock.getInputStream();
        OutputStream os = sock.getOutputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        PrintStream ps = new PrintStream(os);


            String reply = execute(cmd); //this function return "HTTP/1.1 200 OK\r\n\r\nOK\r\n"
            if (reply != null){
              ps.println(reply);
            }
            else {
              br.close();
              ps.close();
              break;
            }

打印流在哪里打印回复? HTML?如何在index.html中阅读此回复?

我试过这种方式

document.getElementById('A1').innerHTML=xmlhttp.status;
document.getElementById('A2').innerHTML=xmlhttp.statusText;
document.getElementById('A3').innerHTML=xmlhttp.responseText;

我从xmlhttp.status得到的是0.但是当我尝试教程时它有以下代码

    xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById('A1').innerHTML=xmlhttp.status;
    document.getElementById('A2').innerHTML=xmlhttp.statusText;
    document.getElementById('A3').innerHTML=xmlhttp.responseText;
    }
  }

然而,它不满足条件,我有点困难几天,迫切需要帮助。

0 个答案:

没有答案