`

struts1+jquery+json

    博客分类:
  • json
阅读更多

1.Struts+JQuery+XML

       struts-config.xml如下:

             
view plaincopy to clipboardprint?
<action 
     attribute="testForm" 
     input="/indexxml.jsp" 
     name="testForm" 
     path="/testxml" 
     scope="request" 
     type="action.TestXmlAction" 
     validate="false" /> 
 <action
      attribute="testForm"
      input="/indexxml.jsp"
      name="testForm"
      path="/testxml"
      scope="request"
      type="action.TestXmlAction"
      validate="false" />             

      TestxmlAction.java如下:

      
package action;  
 
import java.io.IOException;  
import java.io.PrintWriter;  
import java.util.ArrayList;  
import java.util.List;  
 
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
 
import org.apache.struts.action.Action;  
import org.apache.struts.action.ActionForm;  
import org.apache.struts.action.ActionForward;  
import org.apache.struts.action.ActionMapping;  
 
import form.TestForm;  
 
/**  
 * MyEclipse Struts 
 * Creation date: 03-05-2010 
 *  
 * XDoclet definition: 
 * @struts.action path="/test" name="testForm" input="index.jsp" scope="request" 
 */ 
public class TestXmlAction extends Action {  
    /* 
     * Generated Methods 
     */ 
 
    /**  
     * Method execute 
     * @param mapping 
     * @param form 
     * @param request 
     * @param response 
     * @return ActionForward 
     * @throws IOException  
     */ 
    public ActionForward execute(ActionMapping mapping, ActionForm form,  
        HttpServletRequest request, HttpServletResponse response) throws IOException {  
        TestForm testForm = (TestForm) form;// TODO Auto-generated method stub  
        response.setContentType("text/xml; charset=utf-8");//传输xml时要用html  
        response.setCharacterEncoding("utf-8");  
        System.out.println(testForm.getTestvalue());  
        PrintWriter pw=response.getWriter();  
        //1.传递单个参数,注意应将text/xml改为text/html  
        /*int i=9; 
        pw.print(i); 
        pw.flush();*/ 
        //2.生成xml文件返回给html页面,此时list里面为单个String  
       /* StringBuilder xml = new StringBuilder(); 
        List<String> list=new ArrayList<String>(); 
        list.add("aaa"); 
        list.add("bbb"); 
        list.add("ccc"); 
        xml.append("<items>"); 
        for (Object o : list) { 
            xml.append("<item>").append(o).append("</item>"); 
        } 
        xml.append("</items>"); 
        System.out.println(xml); 
        pw.print(xml.toString()); 
        pw.flush();*/ 
        //3.生成xml文件返回给html页面,此时list里面为对象类型  
        /*response.setContentType("text/xml;charset=utf-8"); 
          StringBuilder xml = new StringBuilder(); 
        List<User> list=new ArrayList<User>(); 
        User user1=new User(); 
        User user2=new User(); 
        User user3=new User(); 
        user1.setUsername("username1"); 
        user1.setPassword(1); 
        user2.setUsername("username2"); 
        user2.setPassword(2); 
        user3.setUsername("username3"); 
        user3.setPassword(3); 
         
        list.add(user1); 
        list.add(user2); 
        list.add(user3); 
        xml.append("<items>"); 
        for (int i=0;i<list.size();i++) { 
            xml.append("<itemslist>"); 
            xml.append("<username>").append(list.get(i).getUsername()).append("</username>"); 
            xml.append("<password>").append(list.get(i).getPassword()).append("</password>"); 
            xml.append("</itemslist>"); 
        } 
        xml.append("</items>"); 
        System.out.println(xml); 
        pw.print(xml.toString());*/ 
        return null;  
    }  
          

/*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
package action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import form.TestForm;

/**
 * MyEclipse Struts
 * Creation date: 03-05-2010
 *
 * XDoclet definition:
 * @struts.action path="/test" name="testForm" input="index.jsp" scope="request"
 */
public class TestXmlAction extends Action {
 /*
  * Generated Methods
  */

 /**
  * Method execute
  * @param mapping
  * @param form
  * @param request
  * @param response
  * @return ActionForward
  * @throws IOException
  */
 public ActionForward execute(ActionMapping mapping, ActionForm form,
  HttpServletRequest request, HttpServletResponse response) throws IOException {
  TestForm testForm = (TestForm) form;// TODO Auto-generated method stub
  response.setContentType("text/xml; charset=utf-8");//传输xml时要用html
    response.setCharacterEncoding("utf-8");
  System.out.println(testForm.getTestvalue());
  PrintWriter pw=response.getWriter();
  //1.传递单个参数,注意应将text/xml改为text/html
  /*int i=9;
  pw.print(i);
  pw.flush();*/
  //2.生成xml文件返回给html页面,此时list里面为单个String
       /* StringBuilder xml = new StringBuilder();
        List<String> list=new ArrayList<String>();
        list.add("aaa");
        list.add("bbb");
        list.add("ccc");
        xml.append("<items>");
        for (Object o : list) {
            xml.append("<item>").append(o).append("</item>");
        }
        xml.append("</items>");
        System.out.println(xml);
        pw.print(xml.toString());
        pw.flush();*/
  //3.生成xml文件返回给html页面,此时list里面为对象类型
  /*response.setContentType("text/xml;charset=utf-8");
    StringBuilder xml = new StringBuilder();
        List<User> list=new ArrayList<User>();
        User user1=new User();
        User user2=new User();
        User user3=new User();
        user1.setUsername("username1");
        user1.setPassword(1);
        user2.setUsername("username2");
        user2.setPassword(2);
        user3.setUsername("username3");
        user3.setPassword(3);
       
        list.add(user1);
        list.add(user2);
        list.add(user3);
        xml.append("<items>");
        for (int i=0;i<list.size();i++) {
         xml.append("<itemslist>");
            xml.append("<username>").append(list.get(i).getUsername()).append("</username>");
            xml.append("<password>").append(list.get(i).getPassword()).append("</password>");
            xml.append("</itemslist>");
        }
        xml.append("</items>");
        System.out.println(xml);
        pw.print(xml.toString());*/
  return null;
 }
  
}

       辅助类User:

             
view plaincopy to clipboardprint?
package action;  
 
public class User {  
    private String username;  
    private int password;  
    public String getUsername() {  
        return username;  
    }  
    public void setUsername(String username) {  
        this.username = username;  
    }  
    public int getPassword() {  
        return password;  
    }  
    public void setPassword(int password) {  
        this.password = password;  
    }  

package action;

public class User {
 private String username;
 private int password;
 public String getUsername() {
  return username;
 }
 public void setUsername(String username) {
  this.username = username;
 }
 public int getPassword() {
  return password;
 }
 public void setPassword(int password) {
  this.password = password;
 }
}
 

             

       indexxml.jsp如下:

             
view plaincopy to clipboardprint?
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
<%  
String path = request.getContextPath();  
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
%>  
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
  <head>  
    
    <base href="<%=basePath%>">  
    <title>MyStrutsJQueryJson</title>  
    <meta http-equiv="pragma" content="no-cache">  
    <meta http-equiv="cache-control" content="no-cache">  
    <meta http-equiv="expires" content="0">      
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
    <meta http-equiv="description" content="This is my page">  
    <!--  
    <link rel="stylesheet" type="text/css" href="styles.css">  
    -->  
    <script type="text/javascript" src="/S1.2SHJQuery/js/jquery-1.4.2.js"></script>  
<script type="text/javascript">  
    //1.jquery单独传递单个参数  
    /*$(function(){ 
        alert("start"); 
        $.post("testxml.do",{testvalue:$('#test').val()},function(data){ 
            alert(data); 
        }) 
     })*/ 
     //2.jquery单独传递含单个参数的list,采用的是xml形式  
     $(function(){  
        $.post("testxml.do",{testvalue:$('#test').val()},function(data){  
            var items = data.getElementsByTagName("item");  
            alert(items.length);  
            for(var i=0;i<items.length;i++){  
                alert(items[i].childNodes[0].nodeValue);  
            }  
        })  
     })  
     //3.jquery单独传递含对象类型的list,,采用的是xml形式  
     /*$(function(){ 
        $.post("testxml.do",{testvalue:$('#test').val()},function(data){ 
            var items = data.getElementsByTagName("itemslist"); 
            //循环输出username和password          
            for(var i=0;i<items.length;i++){ 
                    var childs=items[i].childNodes; 
                    for(var j=0;j<childs.length;j++){ 
                     alert(childs[j].firstChild.nodeValue); 
               } 
            } 
        }) 
     }) 
     */ 
       
</script>  
  </head>  
  <body>&nbsp;   
  <form action="/testxml.do">  
  <input type="button" value="JQuery"  id="jquerytest"><br>  
  <input type="text" value="JQuery test" name="test" id="test">  
   <font id="userlogin">登陆</font><span id="loading"></span>     
    <p id="result"></p>     
  </form>  
  </body>  
</html> 
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
 
    <base href="<%=basePath%>">
    <title>MyStrutsJQueryJson</title>
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
 <script type="text/javascript" src="/S1.2SHJQuery/js/jquery-1.4.2.js"></script>
<script type="text/javascript">
 //1.jquery单独传递单个参数
 /*$(function(){
  alert("start");
   $.post("testxml.do",{testvalue:$('#test').val()},function(data){
    alert(data);
   })
  })*/
  //2.jquery单独传递含单个参数的list,采用的是xml形式
  $(function(){
   $.post("testxml.do",{testvalue:$('#test').val()},function(data){
    var items = data.getElementsByTagName("item");
    alert(items.length);
      for(var i=0;i<items.length;i++){
       alert(items[i].childNodes[0].nodeValue);
      }
   })
  })
  //3.jquery单独传递含对象类型的list,,采用的是xml形式
  /*$(function(){
   $.post("testxml.do",{testvalue:$('#test').val()},function(data){
    var items = data.getElementsByTagName("itemslist");
   //循环输出username和password    
      for(var i=0;i<items.length;i++){
        var childs=items[i].childNodes;
        for(var j=0;j<childs.length;j++){
               alert(childs[j].firstChild.nodeValue);
         }
      }
   })
  })
  */
 
</script>
  </head>
  <body>&nbsp;
  <form action="/testxml.do">
  <input type="button" value="JQuery"  id="jquerytest"><br>
  <input type="text" value="JQuery test" name="test" id="test">
   <font id="userlogin">登陆</font><span id="loading"></span>  
    <p id="result"></p>  
  </form>
  </body>
</html>
 

 

 2.Struts+JQuery+JSON

      TestAction如下:

             
view plaincopy to clipboardprint?
/* 
 * Generated by MyEclipse Struts 
 * Template path: templates/java/JavaClass.vtl 
 */ 
package action;  
 
import java.io.IOException;  
import java.io.PrintWriter;  
import java.io.UnsupportedEncodingException;  
import java.util.ArrayList;  
import java.util.List;  
 
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
 
import net.sf.json.JSONArray;  
 
import org.apache.struts.action.Action;  
import org.apache.struts.action.ActionForm;  
import org.apache.struts.action.ActionForward;  
import org.apache.struts.action.ActionMapping;  
 
import form.TestForm;  
 
/**  
 * MyEclipse Struts 
 * Creation date: 03-05-2010 
 *  
 * XDoclet definition: 
 * @struts.action path="/test" name="testForm" input="index.jsp" scope="request" 
 */ 
public class TestAction extends Action {  
    /* 
     * Generated Methods 
     */ 
 
    /**  
     * Method execute 
     * @param mapping 
     * @param form 
     * @param request 
     * @param response 
     * @return ActionForward 
     * @throws UnsupportedEncodingException  
     */ 
    public ActionForward execute(ActionMapping mapping, ActionForm form,  
        HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {  
        TestForm testForm = (TestForm) form;// TODO Auto-generated method stub  
        response.setContentType("text/json; charset=utf-8"); //注意设置为json,如果为xml,则设为xml  
/*      response.setContentType("text/xml; charset=utf-8");传输xml时要用xml 
 *      response.setCharacterEncoding("utf-8"); 
 * */ 
        System.out.println(testForm.getTestvalue());  
        //1.struts1.2+JQuery+Json传递list参数,此时list的类型为String  
        /*List<String> list=new ArrayList<String>(); 
        list.add("string1"); 
        list.add("string2"); 
        list.add("string3"); 
        JSONArray json=JSONArray.fromObject(list); 
        try { 
            PrintWriter out=response.getWriter(); 
            System.out.println(json); 
            out.print(json); 
             
            out.flush(); 
        } catch (IOException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
        }*/ 
        //2.struts1.2+JQuery+Json传递Map参数  
        /*Map<String,String> map=new HashMap<String,String>(); 
        map.put("name1","string1"); 
        map.put("name2","string2"); 
        map.put("name3","string3"); 
        JSONArray json=JSONArray.fromObject(map); 
        try { 
            PrintWriter out=response.getWriter(); 
            System.out.println(json); 
            out.print(json); 
            out.flush(); 
        } catch (IOException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
        }*/ 
        //3.传递单个String值  
        /*String singlepara="{\"name\":'中国'}";//要注意格式 
        JSONObject json=JSONObject.fromObject(test); 
        try { 
            PrintWriter out=response.getWriter(); 
            System.out.println(json); 
            out.print(json); 
            out.flush(); 
        } catch (IOException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
        }*/ 
        //4.struts1.2+JQuery+Json传递User参数  
          
        /*User user1=new User(); 
        user1.setPassword(1); 
        String username = "你好"; 
        user1.setUsername(username); 
        //user1.setUsername(new String(username.getBytes("utf-8"), "iso8859-1")); 
        JSONObject json=JSONObject.fromObject(user1); 
        try { 
            PrintWriter out=response.getWriter(); 
            System.out.println(json); 
            out.print(json); 
             
            out.flush(); 
        } catch (IOException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
        }*/ 
        //5.struts1.2+JQuery+Json传递list参数,此时list的类型为String  
        List<User> list=new ArrayList<User>();  
          
        User user1=new User();  
        user1.setPassword(1);  
        user1.setUsername("u1");  
        User user2=new User();  
        user2.setPassword(2);  
        user2.setUsername("u2");  
        User user3=new User();  
        user3.setPassword(3);  
        user3.setUsername("u3");  
          
        list.add(user1);  
        list.add(user2);  
        list.add(user3);  
        JSONArray json=JSONArray.fromObject(list);  
        try {  
            PrintWriter out=response.getWriter();  
            System.out.println(json);  
            out.print(json);  
              
            out.flush();  
        } catch (IOException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        return null;  
    }  
          

/*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
package action;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import form.TestForm;

/**
 * MyEclipse Struts
 * Creation date: 03-05-2010
 *
 * XDoclet definition:
 * @struts.action path="/test" name="testForm" input="index.jsp" scope="request"
 */
public class TestAction extends Action {
 /*
  * Generated Methods
  */

 /**
  * Method execute
  * @param mapping
  * @param form
  * @param request
  * @param response
  * @return ActionForward
  * @throws UnsupportedEncodingException
  */
 public ActionForward execute(ActionMapping mapping, ActionForm form,
  HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
  TestForm testForm = (TestForm) form;// TODO Auto-generated method stub
  response.setContentType("text/json; charset=utf-8"); //注意设置为json,如果为xml,则设为xml
/*  response.setContentType("text/xml; charset=utf-8");传输xml时要用xml
 *   response.setCharacterEncoding("utf-8");
 * */
  System.out.println(testForm.getTestvalue());
  //1.struts1.2+JQuery+Json传递list参数,此时list的类型为String
  /*List<String> list=new ArrayList<String>();
  list.add("string1");
  list.add("string2");
  list.add("string3");
  JSONArray json=JSONArray.fromObject(list);
  try {
   PrintWriter out=response.getWriter();
   System.out.println(json);
   out.print(json);
   
   out.flush();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }*/
  //2.struts1.2+JQuery+Json传递Map参数
  /*Map<String,String> map=new HashMap<String,String>();
  map.put("name1","string1");
  map.put("name2","string2");
  map.put("name3","string3");
  JSONArray json=JSONArray.fromObject(map);
  try {
   PrintWriter out=response.getWriter();
   System.out.println(json);
   out.print(json);
   out.flush();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }*/
  //3.传递单个String值
  /*String singlepara="{\"name\":'中国'}";//要注意格式
  JSONObject json=JSONObject.fromObject(test);
  try {
   PrintWriter out=response.getWriter();
   System.out.println(json);
   out.print(json);
   out.flush();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }*/
  //4.struts1.2+JQuery+Json传递User参数
  
  /*User user1=new User();
  user1.setPassword(1);
  String username = "你好";
  user1.setUsername(username);
  //user1.setUsername(new String(username.getBytes("utf-8"), "iso8859-1"));
  JSONObject json=JSONObject.fromObject(user1);
  try {
   PrintWriter out=response.getWriter();
   System.out.println(json);
   out.print(json);
   
   out.flush();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }*/
  //5.struts1.2+JQuery+Json传递list参数,此时list的类型为String
  List<User> list=new ArrayList<User>();
  
  User user1=new User();
  user1.setPassword(1);
  user1.setUsername("u1");
  User user2=new User();
  user2.setPassword(2);
  user2.setUsername("u2");
  User user3=new User();
  user3.setPassword(3);
  user3.setUsername("u3");
  
  list.add(user1);
  list.add(user2);
  list.add(user3);
  JSONArray json=JSONArray.fromObject(list);
  try {
   PrintWriter out=response.getWriter();
   System.out.println(json);
   out.print(json);
   
   out.flush();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return null;
 }
  
}

 

      struts-config.xml如下:

             
view plaincopy to clipboardprint?
<action  
      attribute="testForm" 
      input="/index.jsp" 
      name="testForm" 
      path="/test" 
      scope="request" 
      type="action.TestAction" 
      validate="false" /> 
<action
      attribute="testForm"
      input="/index.jsp"
      name="testForm"
      path="/test"
      scope="request"
      type="action.TestAction"
      validate="false" />

       index.jsp如下:

             
view plaincopy to clipboardprint?
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
<%  
String path = request.getContextPath();  
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
%>  
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
  <head>  
    <base href="<%=basePath%>">  
      
    <title>struts+jquery+json</title>  
    <meta http-equiv="pragma" content="no-cache">  
    <meta http-equiv="cache-control" content="no-cache">  
    <meta http-equiv="expires" content="0">      
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
    <meta http-equiv="description" content="This is my page">  
    <!--  
    <link rel="stylesheet" type="text/css" href="styles.css">  
    -->  
    <script type="text/javascript" src="/MyStrutsJQueryJson/js/jquery-1.4.2.js"></script>  
    <script type="text/javascript">  
    /*1.struts1.2+JQuery+Json传递list参数,此时list的类型为String 
        $(function(){ 
            $("#submitbutton").click(function(){ 
            var params={testvalue:$('#test').val()}; 
                $.ajax({ 
                        url:"test.do", 
                        data:params, 
                        type:'post', 
                        dataType:'json', 
                        success:function(data){ 
                        //data值:["string1","string2","string3"] 
                                alert("成功"); 
                                alert(data.length); 
                                for(var j=0;j<data.length;j++) 
                                    { 
                                        alert(data[j]); 
                                    } 
                            }, 
                        error:  function(){ 
                                alert("失败"); 
                            }                    
                }) 
            }) 
        })*/ 
    //2.struts1.2+JQuery+Json传递Map参数  
        /*$(function(){ 
            $("#submitbutton").click(function(){ 
            alert("start"); 
            var params={testvalue:$('#test').val()}; 
                $.ajax({ 
                        url:"test.do", 
                        data:params, 
                        type:'post', 
                        dataType:'json', 
                        success:function(data){ 
                                //alert(data.name1);//缺点是须知道属性名,在JSONArray下 
                                //迭代循环输出 
                                //data值为:[{"name3":"string3","name1":"string1","name2":"string2"}] 
                                    $.each(data[0],function(key,value){ 
                                        alert(key+"  "+value); 
                                    }) 
                            }, 
                        error:  function(){ 
                                alert("失败"); 
                            }                    
                }) 
            }) 
        })*/ 
    //3.struts1.2+JQuery+Json传递String参数  
    /* 
    $(function(){ 
        $("#submitbutton").click(function(){ 
            var params={testvalue:$('#test').val()}; 
                alert("start"); 
                $.ajax({ 
                        url:"test.do", 
                        data:params, 
                        type:'post', 
                        dataType:'json', 
                        success:function(data){ 
                                alert("成功"); 
                                alert(data.name); 
                            }, 
                        error:  function(){ 
                                alert("失败"); 
                            }                    
                }) 
            }) 
    })*/ 
    //4.struts1.2+JQuery+Json传递User参数  
        /*$(function(){ 
            $("#submitbutton").click(function(){ 
            var params={testvalue:$('#test').val()}; 
                $.ajax({ 
                        url:"test.do", 
                        data:params, 
                        type:'post', 
                        dataType:'json', 
                        success:function(data){ 
                        //data值为:{"password":1,"username":"你好"} 
                                alert("成功"); 
                                alert(data.username); 
                                alert(data.password); 
                            }, 
                        error:  function(){ 
                                alert("失败"); 
                            }                    
                }) 
            }) 
        })*/ 
    //5.struts1.2+JQuery+Json传递list参数,此时list的类型为User  
        $(function(){  
            $("#submitbutton").click(function(){  
            var params={testvalue:$('#test').val()};  
                $.ajax({  
                        url:"test.do",  
                        data:params,  
                        type:'post',  
                        dataType:'json',  
                        success:function(data){  
                                alert("成功");  
                                //data值:[{"password":1,"username":"u1"},{"password":2,"username":"u2"},{"password":3,"username":"u3"}]  
                                /*for(var j=0;j<data.length;j++) 
                                    { 
                                        alert(data[j].username); 
                                        alert(data[j].password); 
                                    }*/ 
                                    $.each(data,function(i){  
                                        $.each(data[i],function(key,value){  
                                            alert(key+" "+value);  
                                        })  
                                    })  
                            },  
                        error:  function(){  
                                alert("失败");  
                            }                     
                })  
            })  
        })  
    </script>  
  </head>  
    
  <body>  
    测试输入框:<input type="text" id="test" name="hello"><br>  
    <input type="button" name="submitbutton"  id="submitbutton" value="提交">  
  </body>  
</html> 
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>struts+jquery+json</title>
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
 <script type="text/javascript" src="/MyStrutsJQueryJson/js/jquery-1.4.2.js"></script>
 <script type="text/javascript">
 /*1.struts1.2+JQuery+Json传递list参数,此时list的类型为String
  $(function(){
   $("#submitbutton").click(function(){
   var params={testvalue:$('#test').val()};
    $.ajax({
      url:"test.do",
      data:params,
      type:'post',
      dataType:'json',
      success:function(data){
      //data值:["string1","string2","string3"]
        alert("成功");
        alert(data.length);
         for(var j=0;j<data.length;j++)
          {
           alert(data[j]);
          }
       },
      error: function(){
        alert("失败");
       }     
    })
   })
  })*/
 //2.struts1.2+JQuery+Json传递Map参数
  /*$(function(){
   $("#submitbutton").click(function(){
   alert("start");
   var params={testvalue:$('#test').val()};
    $.ajax({
      url:"test.do",
      data:params,
      type:'post',
      dataType:'json',
      success:function(data){
        //alert(data.name1);//缺点是须知道属性名,在JSONArray下
        //迭代循环输出
        //data值为:[{"name3":"string3","name1":"string1","name2":"string2"}]
         $.each(data[0],function(key,value){
          alert(key+"  "+value);
         })
       },
      error: function(){
        alert("失败");
       }     
    })
   })
  })*/
 //3.struts1.2+JQuery+Json传递String参数
 /*
 $(function(){
  $("#submitbutton").click(function(){
   var params={testvalue:$('#test').val()};
    alert("start");
    $.ajax({
      url:"test.do",
      data:params,
      type:'post',
      dataType:'json',
      success:function(data){
        alert("成功");
        alert(data.name);
       },
      error: function(){
        alert("失败");
       }     
    })
   })
 })*/
 //4.struts1.2+JQuery+Json传递User参数
  /*$(function(){
   $("#submitbutton").click(function(){
   var params={testvalue:$('#test').val()};
    $.ajax({
      url:"test.do",
      data:params,
      type:'post',
      dataType:'json',
      success:function(data){
      //data值为:{"password":1,"username":"你好"}
        alert("成功");
        alert(data.username);
        alert(data.password);
       },
      error: function(){
        alert("失败");
       }     
    })
   })
  })*/
 //5.struts1.2+JQuery+Json传递list参数,此时list的类型为User
  $(function(){
   $("#submitbutton").click(function(){
   var params={testvalue:$('#test').val()};
    $.ajax({
      url:"test.do",
      data:params,
      type:'post',
      dataType:'json',
      success:function(data){
        alert("成功");
        //data值:[{"password":1,"username":"u1"},{"password":2,"username":"u2"},{"password":3,"username":"u3"}]
         /*for(var j=0;j<data.length;j++)
          {
           alert(data[j].username);
           alert(data[j].password);
          }*/
          $.each(data,function(i){
           $.each(data[i],function(key,value){
            alert(key+" "+value);
           })
          })
       },
      error: function(){
        alert("失败");
       }     
    })
   })
  })
 </script>
  </head>
 
  <body>
    测试输入框:<input type="text" id="test" name="hello"><br>
    <input type="button" name="submitbutton"  id="submitbutton" value="提交">
  </body>
</html>

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics