让AJAX工作的问题

时间:2011-04-07 23:13:15

标签: javascript ajax

在使用某个ajax脚本时遇到一些问题。 使用它作为html页面:

<html>
    <head>
        <script type="text/javascript" src="scripts\main.js"></script>
        <link rel="stylesheet" type="text/css" href="css\mainStyle.css" />
    </head>
    <body onload="onloadHandler();">
        <canvas id="canvas" style="background-color:#ddd">
            Sorry, your browser does not support the canvas element.
        </canvas>
    </body>
</html>

剧本:

function onloadHandler()
{   
    canvasItem = document.getElementById('canvas');

    canvasItem.addEventListener('mousedown', mousedownEventHandler, false);
    canvasItem.addEventListener('mousemove', mousemoveEventHandler, false);

    callService("http://www.xul.fr/somefile.xml");
    //  callService("http://allcodecorner.com/index.html");
//  callService("http://stackoverflow.com");
//  callService("http://www.w3schools.com/ajax/ajax_info.txt");
    setTimeout("redraw()", 5);
}

function callService(serviceName)
{
    var xmlhttp;
    if(window.XMLHttpRequest)
    {
        xmlhttp = new XMLHttpRequest();

    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if(xmlhttp.readyState == 0)
        {
            alert('not initialized');
        } else if (xmlhttp.readyState == 1)
        {
            alert('connection established');
        } else if (xmlhttp.readyState == 3)
        {
            alert('processing request');
        } else if (xmlhttp.readyState == 4)
        {
            alert('ready!');
        }

        if(xmlhttp.readyState==4)
        {
            if(xmlhttp.status==200)
            {
                alert(xmlhttp.responseText);
            } else {
                alert('Failed: ' + xmlhttp.responseText + ", status: " + xmlhttp.status);
            }
        }
    }
    alert(serviceName);
    xmlhttp.open("POST",serviceName,true);
    xmlhttp.send(null);
}

无论我输入什么地址,我都会收到消息 '建立连接' “准备好”
'失败:,状态:0'。

我试过firefox和chrome,试过在本地运行并托管,似乎没什么用。我总是得到readyState为4,状态为0 有任何想法吗?我已经尝试过多个网站连接,每次都是同样的事情 还试过GET,设置一些标题,结果相同。几乎尝试了我能找到的每一个例子,没有运气

1 个答案:

答案 0 :(得分:2)

您似乎正在尝试向远程位置发出Ajax请求,由于Same Origin Policy这是不可能的。

不确定是否有修复:如果你控制远程位置,你可以让它发送JSONP。如果不可能,您将不得不使用服务器端代理。

相关问题