`

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>

分享到:
评论

相关推荐

    Struts2+Jquery+JSON 应用例子

    Struts2 Jquery JSON Struts2 Jquery JSON Struts2 Jquery JSON Struts2 Jquery JSON Struts2 Jquery JSON Struts2 Jquery JSON Struts2 Jquery JSON Struts2 Jquery JSON

    Struts2 + jQuery+JSON 实现ajax

    ### Struts2 + jQuery + JSON 实现Ajax 在现代Web开发中,Ajax技术因其能够实现网页的局部刷新而被广泛采用。本篇文章介绍如何利用Struts2框架结合jQuery与JSON来构建一个简单的Ajax功能。 #### 一、环境搭建 1. ...

    json+jquery+struts2+hibernate+spring 实现的小型bbs系统,这个提供包

    json+jquery+struts2+hibernate+spring 实现的小型bbs系统,这个提供包 ,很不错的下载后,好好徐希一下吧

    Struts2+JSON+JQuery实现简单的验证

    Struts2、JSON和JQuery是Web开发中的三个关键技术,它们常常被结合使用来构建高效、动态的用户界面。在本教程中,我们将探讨如何利用这些技术实现一个简单的验证功能。 首先,Struts2是一个基于MVC(Model-View-...

    一个简单的struts2+json+jquery 交互的例子

    Struts2、JSON和jQuery是Web开发中常用的三个技术,它们在构建动态、交互式的Web应用程序时发挥着关键作用。这个例子将展示如何整合这三个工具,实现前后端的数据交换。 首先,Struts2是一个强大的MVC(Model-View-...

    Struts2+jQuery(不用JSON)实现局部刷新

    - **Struts2的JSON插件**:虽然题目要求不使用JSON,但通常情况下,Struts2通过JSON插件返回数据给jQuery是最方便的方式。不过,我们可以通过设置Content-Type为"text/plain"或"text/html",让Struts2返回非JSON...

    struts2+jquery+json+ajax例子

    总结起来,"struts2+jquery+json+ajax"的例子展示了如何利用这些技术协同工作,实现一个无刷新的登录界面,提供流畅的用户体验。通过Struts2处理业务逻辑和数据验证,jQuery和Ajax负责前后端的通信,JSON作为数据...

    struts2+spring+hibernate+jquery+json

    Struts2、Spring、Hibernate、jQuery 和 JSON 是五个在IT行业中极为重要的技术组件,它们各自在Web应用开发中扮演着不同的角色。这篇文章将详细介绍这些技术的整合使用以及它们的功能。 首先,Struts2 是一个基于 ...

    struts2+json+jquery实现ajax数据的存取

    "Struts2+JSON+jQuery实现Ajax数据的存取"就是一个典型的示例,它结合了强大的MVC框架Struts2、轻量级的数据交换格式JSON以及高效的前端库jQuery,以实现网页上的无刷新数据交互。下面将详细介绍这三个技术及其在...

    struts2+jQuery+json实现AJAX.zip

    struts2+jQuery+json实现AJAX.zip

    结合struts2.3.4+jQuery+mysql+json

    结合struts2.3.4+jQuery+mysql+json开发的一个小例子。

    struts2+jquery+json

    Struts2、jQuery和JSON是Web开发中的三个关键技术,它们在构建动态、交互式的Web应用程序时发挥着重要作用。下面将分别对这三个技术进行详细解释,并探讨它们如何协同工作。 Struts2是一个基于MVC(Model-View-...

    struts2+ajax+jquery

    在这个"struts2+ajax+jquery"的主题中,我们将深入探讨如何利用Struts2、jQuery和Ajax技术实现Web页面的异步交互。 首先,Struts2作为MVC框架,它的核心是Action,它负责处理用户的请求,并通过配置的Result返回...

    struts2+json+jquery局部刷新实现注册验证

    struts2+json+jquery局部刷新实现注册验证,包括前台的用户名、密码、手机、身份证、邮箱(包含发邮件技术)、邮箱验证码、验证码的验证,用到的是json+jquery,后台则是用struts2+java类

    struts2+json

    这个资源"struts2+json"显然涉及到在Struts2框架下实现JSON(JavaScript Object Notation)数据交换,这是一种轻量级的数据交换格式,广泛用于前后端交互,特别是AJAX(Asynchronous JavaScript and XML)请求。...

    struts2+json+jquery实现ajax登录和注册功能.pdf

    .struts2+json+jquery实现ajax登录和注册功能.pdf

    struts2+json+jquery实现ajax登录和注册功能.docx

    .struts2+json+jquery实现ajax登录和注册功能.docx

    json+jquery+struts2+ajax

    struts2 json jquery ajax实现用户登陆及业面跳转

    Struts 1.3 +JQuery+Json Post传值

    Struts 1.3 +JQuery+Json Post传值 由于网上关于这个的资料很少,现整理出来,方便大家学习. 关于Json的优势,网上的评价都很高,对于处理复杂的数据相对于处理xml来说要好很多,更多关于这方面的知识读者可以到网上...

Global site tag (gtag.js) - Google Analytics