简体   繁体   中英

How to differentiate between servlet responses in javascript?

In my website i am using ajax to post information to a java servlet and read the response using the following javascript code:

            $.ajax({
            url : 'myfirstservlet',
            async: false,
            data : {
                       //send info..
                   },

            success : function(responseText) {

                //receive response..
            }
        });

And in my servlet i am returning multiple responses. for example:

    String response1 = "response1";
    int response2 = "5";
    out.println(response1);
    out.println(response2);

So how do I get the values of these two different responses and put them in separate javascript variables?

eg

$var response1 = ['response1'];
$var response2 = ['response2'];

Thanks :)

If out is the responsewriter, your output would be

response1
5

One better way would be to create a JSON object instead of plain text.

{
    "res1":"response1",
    "res2":"5"
}

What you want to is respond with two different data in single response. As per HTTP you cannot have two response.

You can do this either by using Json or properly delemating your data.

  • If this response are simple string then go for delimation method Don't use ',' as delimater if the string even remotely may contain comma. Delimator with multiple carractor will do. '#Delem#'
  • If the data is complicated ie object structure with aggrigation and constitutuin then go for JSON.

I think we are over-complicating this.

There is no such thing in HTTP as multiple responses to a request. The client makes a request and the server sends back a response. The code you showed does not send multiple responses. It sends a single response that just has 2 pieces of interesting data in it.

Since you are using println , then your output is by definition line-separated. So in your client-side code, split the response on CRLF.

var parts = response.split(/\r?\n/);
var part1 = parts[0];
var part2 = parts[1];

If the data you are transferring is as simple as this and unlikely to grow, this is fine. If you want a more scalable solution, I recommend JSON.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM