简体   繁体   中英

How to pass multiple values from java servlet to javascript using ajax jquery

I'm newbie on developing Java Servlet. Right now, I know how to pass single value from java servlet to javascript, but I can't find the solution on passing multiple values. Please help me to solve my problem. I'm using jquery for ajax to pass the value from jsp file to java servlet file.

The problem of this is that not getting the value of json object from servlet in ajax.js

Here is my codes so far:

index.jsp:

<fieldset>
<legend>JSP Servlet Practice</legend>
<br>
Enter First Number: <input type="text" id="txt1" />
<br>
<br>
Enter Second Number: <input type="text" id="txt2" />
<br>
<form>
    <input type="radio" name="opt" value="Add" id="opt">Add
    <input type="radio" name="opt" value="Min" id="opt">Minus
    <input type="radio" name="opt" value="Mult" id="opt">Multiply
    <input type="radio" name="opt" value="Div" id="opt">Divide
</form>
<br>
<input type="button" value="Enter" id="btn">
<input type="button" value="Clear" id="btnClear">
<input type="submit" id="btnReverse" value="Reverse Number">

ajax.js: (In this part indicates the event of each button.)

$(document).ready(function() {
$("#btnReverse").click(function() {
    $.get('getTextFromJSP2', {
        txt1 : $('#txt1').val(), txt2 : $('#txt2').val()
    }, function(json) {
        $('#txt1').text(json.txt11);
    });
});

And this is the java servlet file, getTextFromJSP2.java:

@SuppressWarnings("unchecked")
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    clsPL pl = new clsPL();
    String txt1 = request.getParameter("txt1");
    String txt2 = request.getParameter("txt2");
    JSONObject json = new JSONObject();
    json.put("txt11", txt1);
    json.put("txt22", txt2);
    response.setContentType("text/plain");
    response.getWriter().write(json.toString());
}

Thank you in advance.

您可以尝试放置以下内容吗?

response.setContentType("application/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