0

I need to send ajax request to java back-end and to response (from java back-end) with two html-blocks as answer. I want to generate those two html-blocks using two different JSPs. I do this as following:

req.setAttribute(...);
...
resp.setContentType("text/html");
RequestDispatcher dispatcher = req.getRequestDispatcher("one.jsp");
dispatcher.include(req, resp);
dispatcher = req.getRequestDispatcher("two.jsp");
dispatcher.include(req, resp);

And it works. But on the front-end I receive an answer like one solid html code (rendered one.jsp + rendered two.jsp). But I need to receive it as two separate html blocks to put each block to it's own . What is the proper way to do this?

Ajax code:

    function addNew() {
        var request = $.ajax({
            url: "myUrl",
            type: "post",
            dataType: "html",
            success: function(data) {
                $("#divNameOne").html(<one part of data>);
                $("#divNameTwo").html(<second part of data>);
            },
            error:function() {
                alert("fail");
            }
        });
    }
Toro Boro
  • 377
  • 5
  • 16
  • Can you share js code block ? It seems you need to seperate html blocks in your js. If you are okay with single ajax request. – İlker Korkut May 18 '15 at 12:06
  • I've updated question with ajax code. So the only way is to parse code in Java Script? – Toro Boro May 18 '15 at 12:20
  • are you loading an html fragment and inserting it into an existing div?What is the purpose of two html block? Can you give more context? – Francesco Pirrone May 18 '15 at 12:23
  • Sorry, I made a mistake when editing question. Now I updated it one more time. I need to put every html block to it's own div - that is the purpose. – Toro Boro May 18 '15 at 12:28
  • do you have unique ids or classes in your jsps? , so you will be able to select certain block from your data. – İlker Korkut May 18 '15 at 20:56
  • Yes, I have ids. For example I receive this string from java back-end: "
    ...
    _new lines_
    ...
    ". What is the best way to separate this string into two parts (with div1 and div2)?
    – Toro Boro May 19 '15 at 11:24

1 Answers1

0

In your success function ,

var reponseHtml = $(data); // or you can use $($.parseHtml(data));
$("#divNameOne").html(responseHtml.find("#div1").html());
$("#divNameTwo").html(responseHtml.find("#div2").html());

It might work.

İlker Korkut
  • 3,129
  • 3
  • 30
  • 51