Ajax跨域访问后回调函数的问题


Ajax跨域访问bing translator的接口,在url中后面直接加上oncompete=mycallback,但是回调函数却不执行,、、、、、、顺便给解释一下oncomplete,这到底是哪的方法???

<script type="text/javascript">
   function loadXMLDoc(){
    xmlHttpRequest=null;
    if (window.XMLHttpRequest)
      {// code for IE7, Firefox, Opera, etc.

          xmlHttpRequest=new XMLHttpRequest();
      }
    else if (window.ActiveXObject)
      {// code for IE6, IE5
          xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");
      }
     if (xmlHttpRequest!=null)
      {   
          xmlHttpRequest.open("GET","AjaxSer",true); 
          xmlHttpRequest.onreadystatechange=state_Change;
          xmlHttpRequest.send(null);
      }
     else
      {
        alert("Your browser does not support XMLHTTP.");
      }
     function state_Change()
        {  
           if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200){

            var responseText = xmlHttpRequest.responseText;
            var from = "en", to = "Zh-CHS", text = "i love you , China";

            var s = document.createElement("script");

            s.src = "http://api.microsofttranslator.com/V2/Ajax.svc/Translate" +
                "?appId=Bearer " + encodeURIComponent(responseText) +
                "&from=" + encodeURIComponent(from) +
                "&to=" + encodeURIComponent(to) +
                "&text=" + encodeURIComponent(text) +
                "&oncomplete=mycallback";
             document.body.appendChild(s);

            }
        }

       function mycallback(r){
          alert(r);
          document.getElementById("div2").innerHTML = r ;
       }

   }
     </script>

Ajax javaweb JavaScript JSP

huangz 10 years, 8 months ago

官方文档 里的 javascript 示例其实是一个 jsonp

这个 http://api.microsofttranslator.com/V2... 返回给你的结果应该是一个 mycallback(RESULT_OBJECT) 的函数调用,所以在 function loadXMLDoc() 里定义的 function mycallback() 是无法直接执行的,所以你应该可以在调试面板里看到 mycallback 未声明之类的报错

改成 window.mycallback = function(ARGUMENT){ CONTENT } 或者把声明放到 loadXMLDOC 平级就可以了

huandi answered 10 years, 8 months ago

Your Answer