0

您好,我正在尝试 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 Method not allowed

4

1 回答 1

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');

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

您可能希望将其微调为...

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

...为了只允许来自您的域的 CORS 请求。

我找到的关于 CORS 的最佳信息:使用 CORS

于 2013-11-15T05:46:29.327 回答