您的位置:首页 > Web前端 > JQuery

ajax的基本实现和jquery实现

2014-05-22 13:10 190 查看
AJAX即“Asynchronous Javascript
+ XML"(异步javascript和xml),是指一种创建交互网页应用的网页开发技术。

通过在后台与服务器进行少量数据交换,AJAX
可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。

<%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title></title>
<script type="text/javascript" src="../js/jquery-1.4.3.js"></script>
<script type="text/javascript">
function loadXMLDoc1()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML= xmlhttp.responseText;//获取返回值
}
}
xmlhttp.open("GET","/test/tt5",true);
xmlhttp.send();
}

function loadXMLDoc(){
$.ajax({
url:"/test/tt5",
type:'GET',
dataType:'json',//往后台传递参数类型
data:{'days':'2'},//往后台传递参数,如果是传递一个对象,估计要把每个变量和值写成参数,到后台获取存放到类中吧
context: document.body,//让回调函数内 this 指向这个对象,不加也行
success:function(data1){
alert(data1);//data1是从后台传来的参数
}
});
}

</script>
</head>
<body>
<button type="button" onclick="loadXMLDoc()">请求数据</button>
<div id="myDiv"></div>
</body>
</html>


后台用的是springmvc,
@Controller
@RequestMapping("/test")//类级别,可以不需要
public class TestController {
@RequestMapping( value = "/tt5",method = RequestMethod.GET)
public void TT5(HttpServletRequest req,HttpServletResponse res) throws IOException{
PrintWriter writer = res.getWriter();

System.out.println(req.getParameter("days"));//用req.getAttribute()得不到,

JSONObject jo = new JSONObject();//用json的话要添加json包支持
jo.put("name", "fly");
jo.put("type", "虫子");
//ajax后台往前台能传递的参数类型:string,int,list,json
writer.print(jo);//writer.write()也可以,从response中获得的printwriter,不仅会吧参数输入到控制台,还会把参数通过http返回到后台
writer.flush();
writer.close();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: