如何正确发送javascript响应块的ajax请求

时间:2011-11-25 11:27:52

标签: javascript ajax xmlhttprequest

我正在使用ajax调用远程服务器,该服务器应该返回一个javascript块作为响应。我的ajax调用类似于:

    var m3_u = (location.protocol=='https:'?'https://ads.admarvel.com/fam/javascriptGetAd.php':'http://ads.admarvel.com/fam/javascriptGetAd.php');
    var m3_r = Math.floor(Math.random()*99999999999);
    var queryString = '?partner_id='+partnerId;
queryString += '&site_id='+siteId;
queryString += '&target_params=' + targetparams_str;
queryString += '&version=1.5';
queryString += '&language=javascript';
queryString += '&format=wap';
queryString += '&cb='+m3_r;

    if (window.XMLHttpRequest)
                {
                    xmlhttp=new XMLHttpRequest();
                }
                else
                {
                    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                }
                alert(xmlhttp);

                xmlhttp.onreadystatechange=function()
                {
                    alert(xmlhttp.readyState);
                    if (xmlhttp.readyState==4)
                    {
                        alert("response "+xmlhttp.responseXML);
                        console.log(xmlhttp.responseXML);
                        //document.getElementById('ad').innerHTML = xmlhttp.responseText;
                        //document.write("<scr"+"ipt type='text/javascript'>");
                        //document.write(xmlhttp.responseText); 
                        //document.write("<\/scr"+"ipt>");
                    }
                }

                xmlhttp.open("GET",m3_u+queryString,false);

                xmlhttp.setRequestHeader('Content-Type','text/javascript');
                xmlhttp.send();

但我得到的回复是 null 。 当我点击更明亮的网址时,它会正确地返回一个javascript代码块。

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

我认为您正在尝试跨站点XMLHTTPRequest。

您必须以不同方式处理跨站点XMLHttpRequest。如果您使用Java实现,则可以使用以下URL

http://mytechbites.blogspot.com/2009/07/cross-domain-xmlhttprequest-calls.html

否则使用jQuery.ajax。