`
yuxuguang
  • 浏览: 136818 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

java程序使用jquery AJAX

阅读更多

啥也不说了,直接上代码

 

java程序:

response.setContentType("text/xml");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		StringBuffer result = new StringBuffer();
		result.append("<studlist><student><name>任贤齐</name><age>36</age><mail id='email'>rxq@yahoo.cn</mail></student><student><name>程浩</name><age>32</age><mail id='email'>chenghao@sina.com</mail></student></studlist>");
		out.print(result);
		
		out.flush();
		out.close();

 

html写法:

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
  <head>
  	<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="css/styles.css">
	<script language="Javascript" src="js/jquery.js"></script>
  	<script type="text/javascript">
  		$(document).ready(function() {
  			 //失去焦点时发生
			$('#name').blur(function(){
                jQuery.ajax({
                    // 提交的页面
                    url: "servlet/TestJquery",
                    data: "name="+$('#name').html, 
                    ContentType: "text/xml",
                    // 从表单中获取数据
                   	//data: $('#commentform').serialize(), 
                   	// 设置请求类型为"POST",默认为"GET"
                   	type: "POST",           	
                    //返回数据类型
                    dataType: "xml",
                    // 设置表单提交前方法
                    beforeSend: function()
                    {
                       alert('提交前');
                    },
                     // 设置表单提交出错
                    error: function(request) { 
                        alert("表单提交出错,请稍候再试");
                    },
                    success: function(data) {
                    	var str = "";
                         $("student" , data).each(function(i){
				            var name=$("name" , this).text();
				           	str = str + name + "<br />"
				           	//这里能显示student下的email属性。(IE6不可用,FF可用)
				          	alert($("mail" , this).attr("id"));
				        });
				         $('#msg').html(str);
                    }
                });
            });
		});
  	</script>
  </head>
  <body>
    <form id="form" name="form" action="#" method="post">
    	<input type="text" id="name" name="name"><br />
    	<input type="text" name="sex"><br />
    	<input type="text" name="age"><br />
    	<input type="submit" id="subm" name="sub" value="提交">
    	<div id="msg"></div>
    </form>
  </body>
</html>

 

 

另:此方法在ie6下不能取得xml的属性,ff下可以。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics