可能重复:
XmlHttpRequest错误:访问控制允许原始不允许原始null
我是JavaScript Phonegap和AJAX的新手。我正在尝试编写一个简单的Phonegap应用程序,该应用程序将从服务器请求消息,但该应用程序没有响应。当我在chrome浏览器上以文件形式运行脚本时,因为我知道Phonegap就是这样工作的,它显示以下XMLHttpRequest cannot load http://localhost/mpl/getPage.php. Origin null is not allowed by Access-Control-Allow-Origin.
我该怎么解决这个问题?我的代码在下面。
<html>
<head>
<script type="text/javascript">
function getMessage()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("serverReply").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://localhost/mpl/getPage.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="serverReply" onclick="getMessage();"><b>Get message</b></div>
</body>
</html>
我的getPage.php
很简单,它只是
<?php
echo 'cool';
?>
请帮帮我。谢谢。
使用下面的代码
<div id="serverReply"><b><a href="#" onclick="getMessage();">Get message</a></b></div>
而不是
<div id="serverReply" onclick="getMessage();"><b>Get message</b></div>
或尝试此
<html>
<head>
<script type="text/javascript">
function getMessage()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
document.getElementById("serverReply").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://localhost/mpl/getPage.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="serverReply"><b><a href="#" onclick="getMessage();">Get message</a></b></div>
</body>
</html>