不能从HTML5应用程序对本地web服务器进行AJAX调用

Can't make AJAX call to local webserver from HTML5 app

本文关键字:服务器 AJAX 调用 web HTML5 应用程序 不能      更新时间:2023-09-26

我试图使一个简单的AJAX请求从HTML5应用程序到本地web服务器。然而,由于客户端代码不是从web服务器服务,我得到的"Origin null is not allowed by Access-Control-Allow-Origin"错误。

我已经尝试了以下帖子中描述的所有内容,但仍然不起作用:XmlHttpRequest错误:Access-Control-Allow-Origin

如果我在internet托管的服务器上发布我的服务器代码,客户端应用程序工作。但我希望它能与我的本地MAMP服务器一起工作,该服务器运行在同一台笔记本电脑上。

1)在本地web服务器上,我向PHP控制器添加了以下内容:

header('Access-Control-Allow-Origin: *');

2)这是我的HTML5客户端应用程序。JSONP应该不需要,因为服务器支持CORS。

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js"></script>
    <base href='http://192.168.15.12/'></base> <!-- local MAMP server -->     
    <script>
        $(document).ready(function() {
                $('#leadButton').click(function(){
                    $.getJSON(
                        'get/leaderboard',
                        function(data){
                            var leader;
                            leader = "<div> The top leader is from local webserver is: " +  data[0].name + "</div>";
                            $('#leaderboard').append(leader);
                            console.log(data);
                        }
                    );     
                });
        });
    </script>
</head>
<body>
    <div id="leaderboard">Leaderboard
        <button id="leadButton">Get Leaderboard</button>
    </div>
</body>

3)当我从Chrome调用客户端应用程序(文件:///Users/John/Desktop/index.html),并单击leadButton"按钮,这里是结果请求/响应头:

Request URL:http://192.168.15.12/get/leaderboard
Request Method:OPTIONS
Status Code:403 Forbidden
Request Headers
Access-Control-Request-Headers:Origin, X-Requested-With, Accept
Access-Control-Request-Method:GET
Origin:null
Response Headers
Connection:Keep-Alive
Content-Length:227
Content-Type:text/html; charset=iso-8859-1
Date:Thu, 03 Nov 2011 19:03:27 GMT
Keep-Alive:timeout=5, max=100
Server:Apache

我错过了什么?谢谢你的帮助。

我发现问题了:

对本地web服务器(192.168.15.12)的请求需要在$中指定的完整URL。getJSON请求:"http://192.168.15.12/get/leaderboard"

"base"标签没有在jQuery调用的URL前加上"http://192.168.15.12/"

我还需要将以下Apache配置添加到我的。htaccess文件中以启用跨域资源共享(CORS)(在PHP中这样做并不可靠):

 Header set Access-Control-Allow-Origin *

access:

file:///Users/John/Desktop/index.html

行不通。因为file:///和localhost不一样。

您需要访问http://192.168.15.12/index.html才能正常工作