简体   繁体   中英

Jquery Post to Servlet

I have the following code on client side:

      <script src="http://code.jquery.com/jquery-1.5.js"></script>
   <script>
    $(document).ready(function() {
   $("a").click(function() {
   //var orderId =  $("#orderId").val();
   $.post("test", { orderId : "John"},
   function(data) {
     alert("Data Loaded: " + data);
   });
   });
 });
    </script>

Server side:

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        PrintWriter writer =  response.getWriter();
        try{
           String orderId = request.getAttribute("orderId").toString();
           writer.write(orderId);
           writer.close();
           }
       catch(Exception ex)
      {
      ex.getStackTrace();
      }
    }

my

request.getAttribute("orderId")

is null and I'm getting null reference exeption. What am I doing wrong?

I think you want request.getParameter("orderId") . Attributes are only for server side use while processing the request. Parameters contain request data from the client side.

You should use getParameter method instead of getAttribute.

request.getParameter("orderId")

getParameter() will retrieve a value that the client has submitted. Where as you should use getAttribute() when you submit the request to another resource (server side).

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