使用post方法发送跨域请求

时间:2012-11-21 11:58:50

标签: php javascript

如何使用Post方法将Javascript的跨域请求发送到包含大量请求数据的Php文件?

我尝试使用$ .ajax,$ .post但遇到与警告POST失败相同的问题。

这是我的HTML文件[call.html],其中包含Javascript at desktop ::

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>

</head>
<body>
<script type="text/javascript">
$.ajax({
    type: 'POST',
    url: 'http://localhost/GP/ALternate/file.php',
    crossDomain: true,
    data: '{"l":2}',
    dataType: 'json',
    success: function(responseData, textStatus, jqXHR) {
        var value = responseData.someKey;
    alert(value);
  //document.getElementById('w').innerHTML = value.d;
        },
    error: function (responseData, textStatus, errorThrown) {
        alert('POST failed.');
    }
});
</script>

<div id ='w'></div>
</body>
</html>

这是我在localhost上的php [file.php]脚本:

<?php
    header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
    header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
    header('Access-Control-Max-Age: 1000');
    header('Access-Control-Allow-Headers: Content-Type');


 $f= $_GET["l"]; 

 echo "{'d' : '".$f."'}";


?> 

2 个答案:

答案 0 :(得分:-1)

如果您想对其他域发出POST请求,则必须使用Cross-origin resource sharing

您需要为目标服务器添加一些响应标头才能生效。

您可以使用JSONP

进行GET

您可以使用jQuery库来处理大多数客户端复杂性。 $ .POST(...)

答案 1 :(得分:-1)

使用jQuery的getJSON,并启用回调功能。

相关问题