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

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

问题描述

我的问题:我将请求发送到一个servlet从一个JSP的AJAX功能

该servlet处理数据,并返回一个的ArrayList

我的问题是如何处理的ArrayList 里面的AJAX,并将其显示在同一个JSP表。

在code是

 函数ajaxFunction(){

 // VAR URL = codeid.options [codeid.selectedIndex]的.text;
 URL =mstParts caseNo = 9和; CDID = QCYST0020E1;
 //警报(CID);
   VAR HTT prequest;
    如果(window.XMLHtt prequest){
        HTT prequest =新XMLHtt prequest();
    }否则,如果(window.ActiveXObject){
        HTT prequest =新的ActiveXObject(Microsoft.XMLHTTP);
    }
  如果(HTT prequest == NULL){警报(空);}

警报(URL);
    HTT prequest.open(GET,URL,真正的);

   HTT prequest.onreadystatechange =功能(){alertContents(HTT prequest); };
  //htt$p$pquest.setRequestHeader('Content-Type,text / plain的);
    HTT prequest.send(空);

  警报('T1');
}

功能alertContents(HTT prequest){
    如果(HTT prequest.readyState == 4){
        VAR CTYPE = HTT prequest.getResponseHeader(内容类型);
        //document.write(HTT prequest.toString());
      //警报(命令类型);
       // VAR xmlDoc中= HTT prequest.responseText;
        //document.write(xmlDoc.toString());
      //如果(xmlDoc中== NULL){警报(空返回');}
        如果(!HTT prequest.status == 200){
            警报(请求错误的Http code:'+ HTT prequest.status);
        }
        其他
            {
                VAR profileXML =的eval(小于%= request.getAttribute(数据)%>);
                如果(!profileXML = NULL){警报(空); } //其他{警报(profileXML(0)); }
               // HTT prequest.getAttribute(数据);


            }
    }
}
 

解决方案

  VAR profileXML =的eval(小于%= request.getAttribute(数据)%>);
 

首先,我建议你了解JavaScript和JSP之间的墙。 JS完全运行在客户端和JSP / Java的完全运行在服务器端。他们当然不会同步运行,你似乎认为。要了解更多信息,请阅读本博客文章

 函数ajaxFunction()
 

其次,我会建议你使用现有的,强大的,深入开发,维护良好的JavaScript库Ajaxical功能,如 jQuery的代替的重新发明轮子AJAX和战斗/奋斗/使用浏览器的具体问题/故障/行为/痛苦令人担忧。我也建议使用 JSON 为的Java Servlet之间的数据传输格式在服务器和JavaScript的客户端。在Java方面,你可以用伟大的 GSON 库这一点。

下面是与所有提到的技术开球的例子。让我们先从一个Servlet和一个JavaBean:

 公共类JsonServlet延伸的HttpServlet {
    保护无效的doGet(HttpServletRequest的请求,HttpServletResponse的响应)抛出了ServletException,IOException异常{
        名单<数据>表= dataDAO.list();
        response.setContentType(应用/ JSON);
        response.setCharacterEncoding(UTF-8);
        。response.getWriter()写(新GSON()的toJSON(列表)。);
    }
}

公共类数据{
    私人龙ID;
    私人字符串名称;
    私人整型值;
    //添加/生成getter / setter方法​​。
}
 

JsonServlet (你可以任何你想要的名字,这只是一个基本的例子)应该被映射到的web.xml 上的已知 URL模式,让我们使用 / JSON 在这个例子中。类数据刚刚重新presents一排你的HTML表(和数据库表)。

现在,这里是你如何能装载到表的 jQuery.getJSON 帮助:

  $。的getJSON(http://example.com/json功能(名单){
    无功表= $('#TABLEID');
    $每个(列表,功能(索引,数据){
        $('&其中; TR>')appendTo(表)。
            .append($('< TD>)文本(data.id))
            .append($('< TD>)文本(data.name))
            .append($('< TD>)文本(data.value)。);
    });
});
 

TABLEID 当然表示 ID &LT的;表> 有关的元素。

这应该是它。毕竟这是相当简单的,相信我。祝你好运。

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.

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

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