2017-02-10 35 views
1

我正在使用XMLHttpRequest將js文件中的變量發送到同一項目中的java文件。XMLHttpRequest js - > java - > js

我的問題和我的問題是:我怎麼知道我的網址? 下面是js文件

xhttp = new XMLHttpRequest(); 
    var handlerFunction = getReadyStateHandler(xhttp, getValue); 
    xhttp.onreadystatechange = handlerFunction; 
    xhttp.open("POST",/* Location of my java file */,true); 
    xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
    xhttp.send(identMsg); 


    function getValue (body) { 
     var valueBody = body.getElementByTagName("body")[0]; 
    } 

    function getReadyStateHandler(xhttp, responseXmlHandler) { 
     return function(){ 
      if (xhttp.readyState == 4) { 
       if(xhttp.status == 200) { 
        responseXmlHandler(xhttp.responseXML); 
       } else {alert("Http error: " +xhttp.status);} 
      } 
     } 
    } 

和Java代碼

public void doPost (HttpServletRequest xhttp, HttpServletResponse res) throws IOException { 
    String body = null; 
    StringBuilder stringBuilder = new StringBuilder(); 
    BufferedReader bufferedReader = null; 

    try { 
     InputStream inputStream = xhttp.getInputStream(); 
     if (inputStream != null) { 
      bufferedReader = xhttp.getReader(); 
      char[] charBuffer = new char[128]; 
      int bytesRead = -1; 
      while ((bytesRead = bufferedReader.read(charBuffer)) > 0) { 
       stringBuilder.append(charBuffer,0, bytesRead); 
      } 

     } else { 
      stringBuilder.append(""); 
     } 
} catch(IOException ex) { 
    throw ex; 
} finally { 
    if(bufferedReader != null) { 
     try { 
       bufferedReader.close(); 
     }catch (IOException ex2){ 
      throw ex2; 
     } 
     } 
    } 

    body = stringBuilder.toString(); 
    res.setContentType("application/xml");  
    res.getWriter().write(body); 
} 

缺什麼我的代碼?

編輯:我需要在js端獲取URL。

+0

該文件存在於網絡服務器上的路徑? – epascarello

+0

[如何從HttpServletRequest獲取URL的一部分?]的可能的副本(http://stackoverflow.com/questions/14065257/how-to-get-only-part-of-url-from-httpservletrequest) – Andremoniy

回答

0

您可以在js中輸入網址document.location.href