将数据从JSP页面发送到另一个页面中的Javascript

时间:2013-12-24 09:17:33

标签: javascript jquery html ajax jsp

我正在尝试将从JSP页面中的网络获取的数据发送到html文件以显示它,在这里我写了一个ajax函数,但没有数据在html中传入JS。如何解决这个问题??? Ajax的:

$.ajax({
  url:'anr_data.jsp',
  cache:false,
   success:function(data,status){   
    alert(data);    
  },
  error:function(){
     alert("failed to fecth data");
 }
});

这是我的JSP页面 JSP:

<%@page import="java.net.URI"%>

<%@page import="java.io.BufferedReader"%>

<%@page import="org.apache.http.client.methods.HttpGet,java.io.InputStreamReader"%>

<%@page import="java.io.BufferedReader,java.io.IOException"%>

<%@page import="org.apache.http.client.methods.HttpGet,org.apache.http.HttpResponse" %>

<%@page import="org.apache.http.impl.client.DefaultHttpClient" %>

<%@page import="org.apache.http.client.HttpClient" %>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%

// get the input values
double val1 = 10;
double val2 = 12;
HttpResponse response1 ;
int responseCode = 0; 
String errorMsg = "";
try { 
String url = "http://10.138.89.70:9090/anrs";

HttpGet request1 = new HttpGet(url);
HttpClient client = new DefaultHttpClient();
// add request header
//request.addHeader("User-Agent", USER_AGENT);
response1 =  client.execute(request1);

System.out.println("response is "+response1.toString());
responseCode = response1.getStatusLine().getStatusCode();
BufferedReader rd = new BufferedReader(new     InputStreamReader(response1.getEntity().getContent()));

StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
    result.append(line);
}
out.println(result); 
System.out.println("result is "+result);
    } catch (Exception e) {
System.out.print(e.toString());
    errorMsg = "Non-numeric input";
  }
 %>

1 个答案:

答案 0 :(得分:1)

不要在JSP中编写scriptlet ,因为scriptlet不应该在JSP中使用超过十年。学习JSP ELJSTL,并使用servlet作为Java代码 见How to avoid Java Code in JSP-Files?

Soltion

在Ajax函数中调用servlet而不是JSP

的Ajax

$.ajax({
   url:'NetDataServlet',     // call servlet NetDataServlet
   cache:false,
   success:function(data){   
      alert(data);    
   },
   error:function(){
      alert("failed to fecth data");
   }
});  

的Servlet

创建名为NetDataServlet的servlet,并在Get方法内添加以下代码

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws 
                                                         ServletException, IOException {   

 //all your scriptlet code from JSP here
 ......
 .......
 ........
 String mesg = "success"
 response.setContentType("text/plain");  // Set content type of the response.
 response.setCharacterEncoding("UTF-8"); 
 response.getWriter().write(mesg);       // Write response body.
}  

Servlet的部署描述符(web.xml)

<servlet>
  <servlet-name>NetDataServlet</servlet-name>
  <servlet-class>com.stackoverflow.NetDataServlet</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>NetDataServlet</servlet-name>
  <url-pattern>/NetDataServlet/*</url-pattern>
</servlet-mapping>