iteye_10699
iteye_10699
2011-08-18 09:48

为什么Ajax调用后台Action,结果返回回调函数时,在js里没有进入回调函数?

  • ajax
  • javascript

我在js里面通过ajax调用一个action,然后返回结果给回调函数,但是程序始终不进入回调函数callback,请问问题出在哪里了?

<script type="text/javascript">
        function chooseFile(obj)
        {
            $('uploadpictureForm').action = "${pageContext.request.contextPath}/page/uploadPicture.action";
            $('uploadpictureForm').submit();
        }   
        function checkRadio(id)
        {
            if(id=="local")
            {
                $("uploadfile").style.display = "block";
                $("uploadPicture").disabled = false;
            }
            if(id=="server")
            {
                $("uploadfile").style.display = "none";
                $("showImg").style.display = "block";
                var url = "${pageContext.request.contextPath}/page/showPicture.action";
                ajax("post",url,"",callback);
                alert(1);
            }
        }
        function callback(obj)
        {
            alert(2);
        }
    
    </script>

ajax.js:

//ajax的封装
var hand;//回调函数
var xmlHttpRequest;
function createXmlRequest(){
    if(window.XMLHttpRequest){
        xmlHttpRequest = new XMLHttpRequest();
    }else{
        xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
}
//参数1:get/post
//参数2:访问地址
//参数3:发送给服务器的数据
//参数4:回调函数
function ajax(method,url,data,handle){
    createXmlRequest();//先创建核心对象
    hand = handle;
    if(method=="get"){
        url += ("?@new Date()@"+data);
        xmlHttpRequest.onreadystatechange = result;
        xmlHttpRequest.open(method,url,true);
        xmlHttpRequest.send(null);

    }else{
        xmlHttpRequest.onreadystatechange = result;
        xmlHttpRequest.open(method,url,true);
        xmlHttpRequest.setRequestHeader("content-length",data.length); 
        xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        xmlHttpRequest.send(data);
    }
}

//回调处理函数
function result(){
    if(xmlHttpRequest.readyState==4&&xmlHttpRequest.status==200){
        var data = xmlHttpRequest.responseText;
        hand(data);
    }

}

struts.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <package name="test" extends="struts-default" namespace="/page">
        <action name="uploadPicture" class="com.isoftstone.action.UploadPictureAction">
            <result name="success" type="redirect">/index.jsp</result>
        </action>
        <action name="showPicture" class="com.isoftstone.action.ShowPictureAction">
            <result name="ajax"/>
        </action>
    </package>
</struts>
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

12条回答