小编典典

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

jsp

我试图将JSP页面中从网络获取的数据发送到html文件以显示它,在这里我编写了一个ajax函数,但是html中没有数据到达JS。如何解决这个问题???阿贾克斯:

$.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";
  }
 %>

阅读 288

收藏
2020-06-10

共1个答案

小编典典

不要在JSP中编写scriptlet ,因为 scriptlet在JSP中 不应使用超过十年。学习JSPEL和JSTL,并将servlet用于Java代码。

解决

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

阿贾克斯

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

Servlet

使用名称NetDataServlet和内部Get方法创建servlet,添加以下代码

@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>
2020-06-10