如何使用Post方法将跨域请求从Javascript发送到请求数据量较大的Php文件?
我尝试过 $.ajax 、 $.post 但遇到与警报 POST 失败相同的问题。
这是我在桌面上使用 Javascript 的 HTML 文件[call.html]::
<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>
这是我在本地主机上的 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."'}";
?>
最佳答案
使用 jQuery 的 getJSON ,启用回调。
关于php - 使用post方法发送跨域请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13492762/