让AJAX工作的问题

Problem with getting AJAX to work

本文关键字:问题 工作 AJAX      更新时间:2023-09-26

让一些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);
}

无论我输入什么地址,我都会收到消息
建立"连接"
"准备好了"
'Failed:, status: 0'.

我试过火狐和chrome,试过在本地运行和托管,似乎没有任何工作。我总是得到readyState为4,status为0。
什么好主意吗?我试过连接多个网站,每次都是一样的。
也尝试过GET,设置一些标头,结果相同。我几乎尝试了所有我能找到的例子,都没有成功

您似乎正在尝试向远程位置发出Ajax请求,由于同源策略,这是不可能的。

不确定是否有一个解决方案:如果你控制远程位置,你可以让它发送JSONP代替。如果这是不可能的,您将不得不使用服务器端代理。