不能让CORS在chrome和firefox中工作

时间:2013-10-02 09:11:22

标签: jquery cors

你好我试图ajax跨域调用,但标题有问题。我遵循了许多教程,但我无法让它发挥作用。

这是我走了多远:

<html>
<head>
<meta http-equiv="Access-Control-Allow-Origin" content="*">
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" ></script>

<script>

    jQuery.support.cors = true;

    $(document).ready(function() {

        //this would be done in a common script file if you are going to
        //make a lot of these calls
        $.ajaxSetup({ type: 'POST', dataType: 'json', contentType: 'application/json', data: {} });

        $('#btn').click(function() {
             //call the web service with the button is clicked
            $.ajax({ url: 'url_external',
                data: '{ "some_data:data" }', //ensure the data is enclosed in a quote
                            success: function (data) {
                alert('here...success');
            },
            complete: function (data) {
                alert('here');
            }
            });

            //return false to avoid a postback
            return false;
        });

    });
</script>


<div>
    <button id='btn'>Load It</button>
    <div id='sayit'></div>
</div>
</body>
</html>

这只适用于IE9。我错过了什么吗?在Mozilla Firefox和Google Chrome中,选项存在问题, 405方法不允许

1 个答案:

答案 0 :(得分:0)

将此添加到'url_external'服务器上的所有HTTP响应:

<?php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');
header('Access-Control-Allow-Headers', 'Content-Type');

这会在url_external服务器上启用CORS Ajax请求。

你可能想要将其调整为......

header('Access-Control-Allow-Origin: http://yourdomain.com');

...仅允许来自您域名的CORS请求。

我发现的有关CORS的最佳信息:Using CORS