jquery的ajax返回json資料另外一個例子(不繼承json-default)

來源:互聯網
上載者:User

 

package org.lsy.test.ajax.action;import java.io.PrintWriter;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.struts2.ServletActionContext;import org.lsy.test.ajax.service.AjaxService;import org.lsy.test.ajax.service.AjaxServiceImpl;import org.rd.framework.common.container.ContainerManager;import org.rd.framework.struts.action.BodyListAction;import org.rd.framework.struts.action.CommonAction;import org.rd.framework.util.ContextUtil;import com.opensymphony.xwork2.ActionContext;import com.opensymphony.xwork2.ActionSupport;public class CompareDateAction  extends CommonAction {//private AjaxService ajaxService = (AjaxService)ContainerManager.getComponent(AjaxService.AJAX_BEAN_ID);private AjaxService ajaxService = new AjaxServiceImpl();private String result; public String execute() throws Exception{return SUCCESS;}public String isRightDate() throws Exception{//ContextUtil.put("dd","df", ContextUtil.SCOPE_SESSION);ActionContext ctx = ActionContext.getContext();HttpServletRequest req=(HttpServletRequest)ctx.get(ServletActionContext.HTTP_REQUEST);HttpServletResponse resp=(HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);resp.setContentType("text/xml");req.setCharacterEncoding("UTF-8");resp.setCharacterEncoding("UTF-8");PrintWriter pw = resp.getWriter(); String datefrom = ""; String dateto = ""; if(req.getParameter("datefrom")!=null){datefrom=req.getParameter("datefrom").toString();}if(req.getParameter("dateto")!=null){dateto=req.getParameter("dateto").toString();}//"[{'jj':'jjaa'}]"if(datefrom.trim().equals("")||dateto.trim().equals("")){pw.println("Y");this.result="{'re':'Y'}";}else if(ajaxService.isRightDate(datefrom, dateto)){pw.println("Y");//this.result="Y";this.result="{'re':'Y'}";}else{pw.println("N");//this.result="N";this.result="{'re':'N'}";}return NONE;}public String getResult() {return result;}public void setResult(String result) {this.result = result;}}

 

 

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN""http://struts.apache.org/dtds/struts-2.0.dtd"><struts><package name="ajaxutil" extends="struts-default" namespace="/ajaxutil"><!-- ajaxutil begin --><action name="isrightdate" class="org.lsy.test.ajax.action.CompareDateAction" method="isRightDate">     </action><!-- ajaxutil end --></package></struts>

 

<%@ page contentType="text/html; charset=UTF-8"%><%@ taglib uri="/WEB-INF/crm_taglist.tld" prefix="crm"%><%@ taglib uri="/WEB-INF/component.tld" prefix="cx"%><%@ taglib uri="/struts-tags" prefix="s"%><%@ page import="java.util.*,org.lsy.test.work.model.Work"%><%String path = request.getContextPath();  String basepath=request.getScheme()+"://"+                  request.getServerName()+":"+request.getServerPort()+                  request.getContextPath()+"/";%><input type="hidden" id="basepath" value="<%=basepath %>" /><script src="<%=basepath %>work/jquery-1.7.1.min.js"></script><%-- --%><!-- data start --><script src="<%=basepath %>work/ui/jquery.ui.core.js"></script><script src="<%=basepath %>work/ui/jquery.ui.widget.js"></script><script src="<%=basepath %>work/ui/jquery.ui.datepicker.js"></script><link rel="stylesheet" href="<%=basepath %>work/themes/base/jquery.ui.all.css"><link rel="stylesheet" href="<%=basepath %>work/demos/demos.css"><!-- data end --><!-- tabs start -->    <link rel="stylesheet" href="<%=basepath %>work/themes/base/jquery.ui.all.css"><script src="<%=basepath %>work/ui/jquery.ui.tabs.js"></script><!-- tabs end --><script>$(function() {$( "#reviewdate" ).datepicker({showOn: "button",buttonImage: "<%=basepath %>work/demos/images/calendar.gif",buttonImageOnly: true});$( "#reviewdate" ).datepicker( "option", "dateFormat", 'yy-mm-dd');});$(function() {$( "#reviewdatefrom" ).datepicker({showOn: "button",buttonImage: "<%=basepath %>work/demos/images/calendar.gif",buttonImageOnly: true});$( "#reviewdatefrom" ).datepicker( "option", "dateFormat", 'yy-mm-dd');});$(function() {$( "#reviewdateto" ).datepicker({showOn: "button",buttonImage: "<%=basepath %>work/demos/images/calendar.gif",buttonImageOnly: true});$( "#reviewdateto" ).datepicker( "option", "dateFormat", 'yy-mm-dd');});//////////////////////////////////////////$(function() {$( "#tabsquery" ).tabs({collapsible: true});});////////////////////////////////////////////////////////////////////////////////////</script><%  List res=new ArrayList();  if(session.getAttribute("worklist")!=null){  res=(ArrayList)session.getAttribute("worklist");  }%><input type="hidden" id="thelen" value="" /><input type="hidden" id="" value="" /><input type="hidden" id="" value="" /><table>  <tr width="100%">    <td width="50%">                  <table border="1">                 <tr>                    <td>                    <form id="lsy_test_work" name="lsy_test_work" method="post" action="">                                        <!-- 查詢區 start -->                    <div class="demo">                    <div id="tabsquery">                    <ul><li><a href="tabsquery-1">關閉查詢區</a></li></ul>                                        <div id="tabsquery-1">                    <p><strong>開啟查詢區</strong>11</p>                    <p>22                    <table>                     <tr>                     <td>                        作業標題:<input type="text" id="worktitle" value=""/>    <br>                        老師:        <input type="text" id="teacher"  value=""/>    <br>         課程名稱:<input type="text" id="course"  value="">    <br>                        學生姓名:<input type="text" id="student"  value="">    <br>                                                批改日期:從<input type="text" id="reviewdatefrom"    value="">    <br>                        到:<input type="text" id="reviewdateto"    value="">    <br>                                    <br>                        <input type="button" onclick="querywork()"  value="查詢"/>             </td>             </tr>         </table>         </p>         </div>         </div>         </div><!-- End demo -->                  <!-- 查詢區 end -->                             </form>                    </td>                 </tr>                 <tr>                    <td>                            <table  id="maindatatable" border="1">  <tr><th>作業標題</th><th>老師 </th><th>課程名稱</th><th>內容</th><th>學生姓名</th><th>班級名稱</th><th>id</th>  </tr>  <%  if(res!=null){    for(int i=0;i<res.size();i++){        Work ww=(Work)res.get(i);  %>  <tr  onclick="f1(<%=i+1%>)"><td><%=ww.getWorktitle() %></td><td><%=ww.getTeacher() %></td><td><%=ww.getCourse() %></td><td><%=ww.getWorkcontent() %></td><td><%=ww.getStudent() %></td><td><%=ww.getClassname() %></td><td><%=ww.getId() %></td>  </tr>  <%} }%>   </table>                                        </td>                 </tr>            </table>               </td>    <td>           <table>              <form  name="addform" id="addform" action="<%=path%>/work/addwork.action" method=post>              <table><tr>  <td width="30%" align="right">作業標題:</td>  <td><input type="text" id="eworktitle" name="work.worktitle" value=""></td>  <td width="30%" align="right">老師:</td>  <td><input type="text" id="eteacher" name="work.teacher" value=""></td></tr><tr>  <td width="30%" align="right">課程名稱:</td>  <td><input type="text" id="ecourse"  name="work.course"  value=""></td>  <td width="30%" align="right">內容:</td>  <td><input type="text" id="eworkcontent"  name="work.workcontent"  value=""></td></tr><tr>  <td width="30%" align="right">學生姓名:</td>  <td><input type="text" id="estudent"  name="work.student"  value=""></td>  <td width="30%" align="right">班級名稱:</td>  <td><input type="text" id="eclassname"   name="work.classname"  value=""></td></tr><tr>  <td width="30%" align="right">批改日期:</td>  <td><input type="text" id="reviewdate"    value=""></td>  <td width="30%" align="right"></td>  <td></td></tr><tr>  <td width="30%" align="right"></td>  <td><input type="button" id="exinzeng"  onclick="addwork()" value="新增"></td>  <td><input type="button" id="exinzeng"  onclick="delwork()" value="刪除"></td>  <td><input type="button" id="eedit"  onclick="editwork()" value="提交修改"></td></tr><input type="hidden" id="eid"  value="" />              </table>              </form>                                   </table>    </td>  </tr></table><%  String actiontype="";  if(request.getAttribute("actiontype")!=null){  actiontype=(String)request.getAttribute("actiontype");  }%><input type="hidden" id="actiontype" value="<%=actiontype %>" /><script>//var basepath=$("#basepath").val();var basepath=document.getElementById("basepath").value;//alert(basepath);var len = $("#maindatatable tr td").length;var thelen=len/6;function f1(rownum){//alert("dddddd");var str="#maindatatable tr:eq("+rownum+")";document.getElementById("eid").value=$("#maindatatable tr:eq("+rownum+")").children().eq(6).html();document.getElementById("eworktitle").value=$("#maindatatable tr:eq("+rownum+")").children().eq(0).html();document.getElementById("eteacher").value=$("#maindatatable tr:eq("+rownum+")").children().eq(1).html();document.getElementById("ecourse").value=$("#maindatatable tr:eq("+rownum+")").children().eq(2).html();document.getElementById("eworkcontent").value=$("#maindatatable tr:eq("+rownum+")").children().eq(3).html();document.getElementById("estudent").value=$("#maindatatable tr:eq("+rownum+")").children().eq(4).html();document.getElementById("eclassname").value=$("#maindatatable tr:eq("+rownum+")").children().eq(5).html();//alert($("#maindatatable tr:eq(1)").children().eq(1).html());//alert($("#maindatatable tr:eq(1)").children().eq(2).html());//alert($("#maindatatable tr:eq(1)").children().eq(3).html());//alert($("#maindatatable tr:eq(1)").children().eq(4).html());//alert($("#maindatatable tr:eq(1)").children().eq(5).html());//alert($("#maindatatable tr:eq(1)").children().eq(6).html());//alert($(this).html()); //alert($(this).text());}function addwork(){var eworktitle=document.getElementById("eworktitle").value;var eteacher=document.getElementById("eteacher").value;var ecourse=document.getElementById("ecourse").value;var eworkcontent=document.getElementById("eworkcontent").value;var estudent=document.getElementById("estudent").value;var eclassname=document.getElementById("eclassname").value;/*var url=basepath+"work/addwork.do?worktitle="+eworktitle+"&teacher="+eteacher+"&course="+ecourse+"&workcontent="+eworkcontent+"&student="+estudent+"&classname="+eclassname;*///document.getElementById("tt").value=url;//window.location.href=url;document.addform.submit();}function delwork(){var worktitle=document.getElementById("eworktitle").value;var teacher=document.getElementById("eteacher").value;var course=document.getElementById("ecourse").value;var student=document.getElementById("estudent").value;var workcontent=document.getElementById("eworkcontent").value;var classname=document.getElementById("eclassname").value;var id=document.getElementById("eid").value;var url=basepath+"work/delwork.action?worktitle="+worktitle+"&teacher="+teacher+"&course="+course+"&student="+student+"&workcontent="+workcontent+"&classname="+classname+"&id="+id;//alert("del--"+url);window.location.href=url;}function editwork(){var worktitle=document.getElementById("eworktitle").value;var teacher=document.getElementById("eteacher").value;var course=document.getElementById("ecourse").value;var student=document.getElementById("estudent").value;var workcontent=document.getElementById("eworkcontent").value;var classname=document.getElementById("eclassname").value;var id=document.getElementById("eid").value;var url=basepath+"work/editwork.action?worktitle="+worktitle+"&teacher="+teacher+"&course="+course+"&student="+student+"&workcontent="+workcontent+"&classname="+classname+"&id="+id;window.location.href=url;}    function querywork(){var worktitle=document.getElementById("worktitle").value;var teacher=document.getElementById("teacher").value;var course=document.getElementById("course").value;var student=document.getElementById("student").value;var url=basepath+"work/querywork.action?worktitle="+worktitle+"&teacher="+teacher+"&course="+course+"&student="+student;//alert("查詢--"+url);window.location.href=url;}            var actiontype=document.getElementById("actiontype").value;    if(actiontype=='otherquery'){    var url=basepath+"work/querywork.action";window.location.href=url;    }////////////////////////////////////////////////$(document).ready(function(){//hideCol(1);//隱藏第二列//$('table td').find('td:eq(1)').hide();//$('table tr').find('td:eq(1)').hide();//$('#maindatatable td').find('td:eq(0)').hide();//$('#maindatatable tr').find('td:eq(0)').hide();var len = $("#maindatatable tr td").length;var thelen=len/6;//var len = $("#mm tr td").length;//alert(len/6);//alert("表行數"+thelen);$("#thelen").val(thelen);$("#reviewdatefrom").change( function () { var date1=$("#reviewdatefrom").val();var date2=$("#reviewdateto").val();var url=basepath+"ajaxutil/isrightdate.action?reviewdatefrom="+date1+"&reviewdateto="+date2;alert($("#reviewdatefrom").val()+"\r"+url); jQuery.ajax( {          url:url,          type:'post',          async:false,          dataType: "text",        //data:'sql='+'hkhkhhhkhk',          success:function(result){        alert("from-----333----"+result);             if(""!=result){                   alert("from---------"+result);              }         }       }); });//end blur$("#reviewdateto").change( function () { var date1=$("#reviewdatefrom").val();var date2=$("#reviewdateto").val();var url=basepath+"ajaxutil/isrightdate.action?reviewdatefrom="+date1+"&reviewdateto="+date2;alert($("#reviewdateto").val()+"\r"+url);$.get(url, function(result){  alert("Data hhss: " + result);});//end get});//end blur});//end ready/////////////////////////////////////////</script>

 

 

 

在這個例子中private String result;其實是沒有用的,我們一般會這樣配置

<struts>
 <package name="ajaxutil" extends="json-default" namespace="/ajaxutil">
  <!-- ajaxutil begin -->
  
  <action name="isrightdate" class="org.lsy.test.ajax.action.CompareDateAction" method="isRightDate">
      
       <result name="success" type="json">
           <param name="root">result</param> 
       </result>
  </action>
  
  <!-- ajaxutil end -->
 </package>
</struts>

 

並且ajax這樣寫:

jQuery.ajax( { 
           url:url, 
           type:'post', 
           async:false, 
           dataType: "json",
           //data:'sql='+'hkhkhhhkhk', 
           success:function(result){
            alert("from-----333----"+result);
               if(""!=result){ 
                    alert("from---------"+result); 
               } 
          } 
        });

這樣我們把要返回的值指定放到java類的resuest變數中,在xml指定返回成功後去這個參數的值給ajax的

回呼函數。

而在我這個例子中,我們繼承的是extends="struts-default",沒有返回,在java類中返回NONE。

ajax中dataType: "text",這樣返回的內容就不是到private String result;了,而是pw.println("Y");

(pw是PrintWriter pw = resp.getWriter();),返回結果用PrintWriter輸出給回呼函數。

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.