日期:2014-05-16  浏览次数:20657 次

ajax开发应用
ajax在很多程序员的眼里是一个很复杂或陌生的字眼,其实, AX并不复杂,自从AJAX技术出来后,天花乱坠的框架纷纷出台,搞得技术开发人员无从下手,baidu google里也有很多例子,大都是非常复杂。

  其实就web开发而言,AJAX技术只是一个配合,完全没有必要本末倒置,是一种页面优化的技术,也就是说,如何去优化我们的web页面才是AJAX的重头戏。下面我举个很简单的例子,可以满足大部分的业务需求。(当然,如果是很专业的页面要求,可以去参考那些复杂的框架)

  第一步:写一个后台的“接口”,这个可以用任何语言来实现,只要能返回http报文就可以了,我这里以webwork后台代码举个例子

public String hotWeek() throws Exception{
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/xml; charset=gb2312");
        PrintWriter out = response.getWriter();
        StringBuffer insertHotHtml = new StringBuffer();
        insertHotHtml.append(" <table width=171 border=0 align=center cellpadding=0
cellspacing=0>   ");
            insertHotHtml.append("<tr> ");
            insertHotHtml.append("<td width=23 height=25></td>  ");
            insertHotHtml.append("</tr> ");
        insertHotHtml.append("</table> ");
        out.print(insertHotHtml.toString());  //返回一个有表格的HTTP报文
        return null;
    }


    不用java的朋友根本不用管这些,只要记住,能返回一个HTTP报文,比如一个静态网页也可以。

  第二步 :在页面里加入下面这段javascript代码

var xmlHttp;
function createXMLHttpRequest(){
    if (window.ActiveXObject){
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest){
        xmlHttp = new XMLHttpRequest();
    }
}
function startAjaxRequest(method,async,actionUrl,data, invokeMethod){
    createXMLHttpRequest();
    xmlHttp.open(method, actionUrl, async);
    xmlHttp.onreadystatechange = handleStateChange;
    xmlHttp.send(data);
    function handleStateChange(){
        if(xmlHttp.readyState == 4){
            if(xmlHttp.status == 200){
                var nodeId = xmlHttp.responseText;
                if (nodeId=='noPermission'){
                    alert('你没有权限访问此操作!');
                }else if( (falseIndex = nodeId.indexOf("false||"))!= -1 ){
                   alert('操作失败,可能的原因为:' + nodeId.substring(
falseIndex+7, nodeId.length) + "!");
                }else if(nodeId=='false'){
                    alert('操作失败,请和管理员联系!');
                }else ...{
                    if (invokeMethod == undefined){
      &n