# Ajax入门及基本开发 ##
# Ajax的基本概念
>> 概念;
界面异步传输技术;
将几种技术和在一起进行开发的一种编程方式;
>> 基本应用场景;
> Google Suggest
> Gmail
> Google Map
# Ajax的开发步骤;
>> 创建XMLHttpRequest对象;
>> 将状态触发器绑定到一个函数;
>> 使用open函数建立与服务器的链接;
>> 向服务器端发送数据;
>> 在回调函数中对返回数据进行处理;
# 简单示例;
>> 简单的弹框操作;
// 创建XMLHttpRequest对象;
<script type="text/javascript">
function createXMLHttpRequest()
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("您的浏览器不支持AJAX!");
return false;
}
}
}
}
</script>
// 将状态触发器绑定到一个函数;
var xmlHttp= createXMLHttpRequest();
xmlHttp.onreadystatechange= function(){
// 在回调函数中对返回数据进行处理;
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
//具体代码;
alert(xmlHttp.responseText);
//在客户端显示结果;
}
}
};
// 使用open函数建立与服务器的链接;
xmlHttp.open("GET","提交的地址,注意跟上应用名",true);
// 向服务器端发送数据;
xmlHttp.send(null);
//POST方式提交数据;
xmlHttp.open("POST","提交的地址,注意跟上应用名",true);
xmlHttp.setRequsetHeader("Content-Type","application/x-www-from-urlencoded");
xmlHttp.send("username=XXX& age=10");
>> 创建一个Servlet
response.setContentType("text/html;charset=UTF-8);
String username= request.getParameter("username");
username= new String(username.getByte("iso-8859-1"),"UTF-8");
syso(username);//服务端返回结果;
//post提交数据的代码;
requset.setCharacterEncoding("UTF-8");
String username= request.getParameter("username");
response.getWriter().write("xxxx");
# Ajax的优化
因为返回数据冗余过多,考虑通过优化格式的方式来进行数据返回;
>> JSON数据格式;
|-- 一种轻量级的数据格式,容易阅读且解析方便;
|-- 基本格式;
> <script>
var student= {"name":"cgx","age":"20"}; //JSON字符串;
alert(students.name+" --- "+students.age);
var students= [ {"name":"cgx","age":"20"}, {"name":"aj","age":"18"}];
alert(students[0].name+" --- "+student[0].age);
//JSON数据格式的数组;
</script>
|-- 使用方式;
> 有个JSON-lib的小型插件
|-- 具体方式;
> JSONArray json= JSONArray.fromObject(Object[] obj);
//对于数组和list集合的转换;
> JASONObject json2= JASONObject.fromObject(Object obj);
//对于单个元素或者Bean 的转换;