在 AJAX 中处理 servlet 输出 [英] Handling servlet output in AJAX

查看:27
本文介绍了在 AJAX 中处理 servlet 输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题:我从 JSP 中的 AJAX 函数向 servlet 发送请求.

servlet 处理数据并返回一个 ArrayList.

我的问题是如何处理 AJAX 中的 ArrayList,并在同一个 JSP 中将其显示为表格.

代码是

function ajaxFunction ( ) {//var url= codeid.options[codeid.selectedIndex].text;url="mstParts?caseNo=9&cdid=QCYST0020E1";//警报(cid);var httpRequest;如果(window.XMLHttpRequest){httpRequest = new XMLHttpRequest();} else if (window.ActiveXObject) {httpRequest = new ActiveXObject("Microsoft.XMLHTTP");}if (httpRequest == null){ alert('null');}警报(网址);httpRequest.open("GET", url, true );httpRequest.onreadystatechange = function() { alertContents(httpRequest);};//httpRequest.setRequestHeader('Content-Type', 'text/plain');httpRequest.send(null);警报('t1');}功能警报内容(httpRequest){如果(httpRequest.readyState == 4){var cType =httpRequest.getResponseHeader("Content-Type");//document.write(httpRequest.toString());//警报(cType);//var xmlDoc=httpRequest.responseText;//document.write(xmlDoc.toString());//if (xmlDoc == null) {alert('null返回');}如果(!httpRequest.status == 200){alert('请求错误.Http 代码:' + httpRequest.status);}别的{var profileXML = eval(<%=request.getAttribute("data")%>);if ( profileXML != null){ alert('null');}//else { alert(profileXML(0));}//httpRequest.getAttribute("data");}}}

解决方案

var profileXML = eval(<%=request.getAttribute("data")%>);

首先,我建议您了解一下 JavaScript 和 JSP 之间的墙.JS 完全在客户端运行,而 JSP/Java 完全在服务器端运行.它们当然不会像您想象的那样同步运行.要了解更多信息,请阅读这篇博客文章.

<块引用>

函数ajaxFunction()

其次,我建议您使用一个现有的、健壮的、开发彻底的、维护良好的 JavaScript 库,它具有 Ajaxical 功能,例如 jQuery 而不是重新发明 AJAX 轮子和与浏览器特定问题/麻烦/行为/痛苦作斗争/挣扎/担心.我还建议使用 JSON 作为服务器上的 Java Servlet 和 JavaScript 之间的数据传输格式在客户端.在 Java 方面,您可以为此使用出色的 Gson 库.

这是一个包含所有提到的技术的启动示例.让我们从一个 Servlet 和一个 JavaBean 开始:

public class JsonServlet extends HttpServlet {protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {列表<数据>list = dataDAO.list();response.setContentType("application/json");response.setCharacterEncoding("UTF-8");response.getWriter().write(new Gson().toJson(list));}}公共类数据{私人长ID;私人字符串名称;私有整数值;//添加/生成 getter/setter.}

JsonServlet(您可以随意命名,这只是一个基本示例)应该映射到 web.xml 中的已知 url-模式,让我们在这个例子中使用/json.Data 类只代表 HTML 表(和数据库表)的一行.

现在,您可以在 jQuery.getJSON 的帮助下加载表格:

$.getJSON("http://example.com/json", function(list) {var table = $('#tableid');$.each(list, function(index, data) {$('').appendTo(table).append($('<td>').text(data.id)).append($('<td>').text(data.name)).append($('<td>').text(data.value));});});

tableid 当然表示

元素的 id.

应该是这样.毕竟这相当简单,相信我.祝你好运.

My problem: I am sending a request to a servlet from an AJAX function in a JSP.

The servlet processes the data and returns a ArrayList.

My question is how to handle the ArrayList inside AJAX, and display it as a table in same JSP.

The code is

function ajaxFunction ( ) {

 // var url= codeid.options[codeid.selectedIndex].text;
 url="mstParts?caseNo=9&cdid=QCYST0020E1";
 //  alert(cid);
   var httpRequest;
    if (window.XMLHttpRequest) {
        httpRequest = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
  if (httpRequest == null){ alert('null');}

alert(url);
    httpRequest.open("GET", url, true );

   httpRequest.onreadystatechange = function() { alertContents(httpRequest); };
  //httpRequest.setRequestHeader('Content-Type', 'text/plain');
    httpRequest.send(null);

  alert('t1');
}

function alertContents(httpRequest) {
    if (httpRequest.readyState == 4) {
        var cType =httpRequest.getResponseHeader("Content-Type");
        //document.write(httpRequest.toString());
      // alert(cType);
       // var xmlDoc=httpRequest.responseText;
        //document.write(xmlDoc.toString());
      //  if (xmlDoc == null) {alert('null returned');}
        if (!httpRequest.status == 200) {
            alert('Request error. Http code: ' + httpRequest.status);
        }
        else
            {
                var profileXML = eval(<%=request.getAttribute("data")%>);
                if ( profileXML != null){ alert('null'); }//else { alert(profileXML(0)); }
               // httpRequest.getAttribute("data");


            }
    }
}

解决方案

var profileXML = eval(<%=request.getAttribute("data")%>);

Firstly, I would recommend you to learn about the wall between JavaScript and JSP. JS runs entirely at the client side and JSP/Java runs entirely at the server side. They certainly doesn't run in sync as you seem to think. To learn more, read this blog article.

function ajaxFunction ( )

Secondly, I would recommend you to use an existing, robust, thoroughly-developed, well-maintained JavaScript library with Ajaxical capabilities such as jQuery instead of reinventing the AJAX wheel and fighting/struggling/worrying with browser specific issues/troubles/behaviors/pains. I would also recommend to use JSON as data transfer format between Java Servlet at server and JavaScript at client. In the Java side you can use the great Gson library for this.

Here's a kickoff example with all of the mentioned techniques. Let's start with a Servlet and a JavaBean:

public class JsonServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Data> list = dataDAO.list();
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(new Gson().toJson(list));
    }
}

public class Data {
    private Long id;
    private String name;
    private Integer value;
    // Add/generate getters/setters.
}

The JsonServlet (you may name it whatever you want, this is just a basic example) should be mapped in web.xml on a known url-pattern, let's use /json in this example. The class Data just represents one row of your HTML table (and the database table).

Now, here's how you can load a table with help of jQuery.getJSON:

$.getJSON("http://example.com/json", function(list) {
    var table = $('#tableid');
    $.each(list, function(index, data) {
        $('<tr>').appendTo(table)
            .append($('<td>').text(data.id))
            .append($('<td>').text(data.name))
            .append($('<td>').text(data.value));
    });
});

The tableid of course denotes the idof the <table> element in question.

That should be it. After all it's fairly simple, believe me. Good luck.

这篇关于在 AJAX 中处理 servlet 输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆