>  기사  >  웹 프론트엔드  >  jquery에서 ajax를 요청하고 서블릿에서 ajax를 응답합니다.

jquery에서 ajax를 요청하고 서블릿에서 ajax를 응답합니다.

php中世界最好的语言
php中世界最好的语言원래의
2018-03-15 10:06:211516검색

이번에는 jquery의 요청 ajax와 servlet의 응답 ajax, jquery의 요청 ajax 및 servlet의 응답 ajax에 대한 주의사항을 알려드리겠습니다. 다음은 실제 사례입니다. 시간.

jsp에서는 먼저 jquery 선반 패키지를 가져와야 합니다.

반환 가능한 사이트의 루트 경로 가져오기:

<% 
  String path = request.getContextPath(); 
%>

jquery에서 ajax 요청 쓰기:

<script type="text/javascript">
     $(function(){
        $(".B").click(function(){
        $.ajax({
            type: "GET",
                     //对应servlet中的方法
            url: "<%=path%>" + "/queryEvaluateByuserId.do",
                     //返回是json数据
            dataType: "json",
            async:false,
           data:{
            },
            success: function(data){
              str = "";
               if(data != null){
                               //循环表单列表
                 for (var i in data)
                  {
                     var num = parseInt(i) + 1 ;                         
                    str +="<tr><td>" + num + "</td><td>" 
                    + data[i]['name'] + "</td><td>"
                    + data[i]['price'] + "元</td>" 
                    + "</tr>";
                  }
                 $(".trtd4").after(str);
               }else{
                 
               }
               
            },
            error: function(data){
            }
          }) 
      });
     }
</script>

jsp 부분:

<p class="tab-pane" id="B" style="text-align:center;"> 
          <p class="row marg" > 
            <table border="2 " style="width:80%;text-align:center;"> 
              <tr class="trtd4"> 
                <th>序号</th> 
                <th>业主名</th> 
                <th>金额</th> 
              </tr>              
            </table> 
          </p> 
        </p>

Alibaba의 빠른 json 변환 패키지 com.alibaba.fastjson.JSON은 서블릿에서 사용됩니다:

private void queryEvaluateByuserId(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException, ServletException{
			HttpSession session=request.getSession();
			request.setCharacterEncoding("UTF-8");
			response.setContentType("text/html");
			response.setCharacterEncoding("UTF-8");
			Cookie[] cookies = request.getCookies();
			int ownerId = 0;
			for (int i = 0; i < cookies.length; i++) {
	      Cookie cookie = cookies[i];
	      if (cookie.getName().equals("ownerId")) {
	      	ownerId = Integer.parseInt(cookie.getValue()); 
	      }
			}
			List<Order> orderList = new ArrayList<>();
			List<Evaluate> queryEvaluateList = new ArrayList<>();
			orderList = orderServiceImpl.queryOrderList(ownerId, null, null, null, null, null);
			List<Map<String, String>> workers = new ArrayList<Map<String, String>>(); 
			for(int i = 0;i < orderList.size();i++){
				Map<String,String> order = new HashMap<String, String>();
				order.put("description", orderList.get(i).getDescription());
				order.put("name", orderList.get(i).getOwnerName());
				System.out.println(orderList.get(i).getDescription());
				order.put("type",orderList.get(i).getTypeName());
				queryEvaluateList = orderServiceImpl.queryEvaluateListByUserId(orderList.get(i).getId());
				order.put("comment", queryEvaluateList.get(0).getComment());
				List<Allocation> allocation = orderServiceImpl.queryAllocationByOrderId(orderList.get(i).getId());
				order.put("price", String.valueOf(allocation.get(0).getPrice()));
				 System.out.println(order);
				workers.add(order);
			}
            //将map键值对转换成json,传给jsp
            response.getOutputStream().write(JSON.toJSONBytes(workers));
		}

이 기사의 사례를 읽은 후 방법을 마스터했다고 믿습니다. PHP 중국어 웹사이트의 다른 관련 기사도 주목해주세요!

추천 자료:

jquery를 구현하여 시작 페이지에서 즉시 데이터를 로드하세요

jquery를 사용하여 입력 상자의 텍스트 콘텐츠를 조작하세요

입력 상자와 드롭 간의 연결 효과 달성 -down box

Jquery 드롭다운 상자 동적 데이터 수집을 달성하는 방법

위 내용은 jquery에서 ajax를 요청하고 서블릿에서 ajax를 응답합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.