在Firefox中通过AJAX跨域访问Web资源
本文为原创,如需转载,请注明作者和出处,谢谢!一、解决在firefox中无法跨域访问的问题
AJAX从本质上讲就是命名用XMLHttpRequest组件来向服务端发送HTTP请求,请接收相应信息。至于成功接收到响应信息后的操作,就和普通的Web客户端程序类似了(一般用DOM将信息加到HTML组件中)。但问题就发生在了XMLHttpRequest组件上。虽然在大多数浏览器中(包括IE、Firefox等)都叫这个名子。使用方法也类似。但在进行某些操作时却有不同的效果。
就拿跨域访问的问题来说。让我们先看看如下的html中的javascript代码:
test.html
<div style="border: 1px solid rgb(204, 204, 204); padding: 4px 5px 4px 4px; background-color: rgb(238, 238, 238); font-size: 13px; width: 98%;"><!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--><html>
<head>
<title></title>
<metahttp-equiv="Content-Type"content="text/html;charset=UTF-8">
<scripttype="text/javascript">
//获得IE和firefox浏览器中的XMLHttpRequest对象
functiongetXMLHTTPRequest()
{
varmyRequest=null;
if(window.XMLHttpRequest)//firefox
{
myRequest=newXMLHttpRequest();
}
elseif(typeofActiveXObject!="#ff0000")//IE
{
myRequest=newActiveXObject("Microsoft.XMLHTTP");
}
returnmyRequest;
}
varmyRequest;
functiononReadyState()//XMLHttpRequest处理异步访问状态时的事件
{
if(myRequest.readyState==4)//4表示成功获得相应信息
{
varmsg=document.getElementById("msg");
msg.value=myRequest.responseText
}
}
functiongetServiceText()
{
myRequest=getXMLHTTPRequest();
if(myRequest)
{
myRequest.onreadystatechange=onReadyState;
try
{
myRequest.open("post","http://www.blogjava.net",true);
}
catch(exception)
{
varmsg=document.getElementById("msg");
msg.value=exception;
}
myRequest.send("test");
}
}
</script>
</head>
<body>
<inputid="msg"type="text"/>
<inputtype="button"value="信息"onclick="getServiceText()"/>
</body>
</html>
页:
[1]