猿问

使用 Spring MVC 将值从 AJAX 传递到控制器

这是html代码


  <ul id="myUL">

    <c:forEach var="userBean" items="${list}">   

    <li id="username"><a href="#">${userBean.username}</a></li>

    </c:forEach>  

    </ul>

<div class="card">

<p>${userBean.phoneno}</p>

<p>${userBean.Address}</p>

</div>

这是 AJAX


<script>

  $("#myUL").click(function(){

      var username=$('#username').val();

      $.ajax({

            url: "details",

            type: 'GET',

            data: {username:username},

            success: function(data){

                   $("#card").html(data);

         }


      });

  });

  </script>

这是控制器代码


@RequestMapping(value="details", method = RequestMethod.POST)

    @ResponseBody

    public ModelAndView details(@RequestParam UserBean userBean, HttpServletRequest request, HttpServletResponse response)

    {

        ModelAndView view = new ModelAndView();

        String username=userBean.getUsername();

        if(retrieveService.getdetail(userBean)!= null)

        {

            view.setViewName("welcomes");

        }

        return null;


    }

我不知道如何将 AJAX 中的值传递给控制器。这是示例输出


Name                  Details

john                  john

smith                 phoneno. 324242

                      Address:xyz

如果我点击名称即<li>标签。它将显示从 MySQL 到 JSP 的详细信息


长风秋雁
浏览 131回答 3
3回答

眼眸繁星

将您的 JavaScript 代码更改为:<script>&nbsp; &nbsp; $("#myUL").click(function(){&nbsp; &nbsp; &nbsp; &nbsp; var username=$('#username').val();&nbsp; &nbsp; &nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url: "details",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type: 'POST',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data: {username:username},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; success: function(data) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$("#card").html(data);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; });</script>并将您的控制器代码更改为:@PostMapping(value = "details")&nbsp; &nbsp; public ModelAndView details(@RequestBody UserBean userBean, HttpServletRequest request,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; HttpServletResponse response) {&nbsp; &nbsp; &nbsp; &nbsp; ModelAndView view = new ModelAndView();&nbsp; &nbsp; &nbsp; &nbsp; String username = userBean.getUsername();&nbsp; &nbsp; &nbsp; &nbsp; if (retrieveService.getdetail(userBean) != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; view.setViewName("welcomes");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; return view;}

哔哔one

您还应该使用 @RequestBody 而不是 @RequestParam 因为它是一个 POST 并且您在正文中而不是在 url 中发送数据。

哈士奇WWW

您正在向接收 POST 请求的控制器发送 GET 请求?
随时随地看视频慕课网APP

相关分类

Java
我要回答