我正在尝试通过Ajax Post方法将一些数据发送到PHP。为了测试它,JS和PHP都在同一个包中。我已经读过,我需要启用它们的跨域操作才能工作并按照说明进行操作。但我仍然从控制台收到此错误:POST http://localhost:8000/php/ajax-follow.php 405(方法不允许) 对象{readyState:4,responseText:“↵... localhost:8000↵↵↵↵”,状态:405,statusText:“方法不允许”}
Javascript代码:
$(function(){
$('#followbtn').on('click', function(e){
e.preventDefault();
$('#followbtn').fadeOut(300);
$.ajax({
url: 'php/ajax-follow.php',
type: 'post',
data: {'action': 'follow', 'userid': '11239528343'},
success: function(data, status) {
if(data == "ok") {
$('#followbtncontainer').html('<p><em>Following!</em></p>');
var numfollowers = parseInt($('#followercnt').html()) + 1;
$('#followercnt').html(numfollowers);
}
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // end ajax call
});
ajax-follow.php的代码
<?php
header("Access-Control-Allow-Origin: http://localhost:8000");
header("Access-Control-Allow-Credentials: true ");
header("Access-Control-Allow-Methods: OPTIONS, GET, POST");
header("Access-Control-Allow-Headers: Content-Type, Depth, User-Agent, X-File-Size,
X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control");
if($_POST['action'] == "follow") {
$file = fopen("test.txt","w");
echo fwrite($file,"Hello World. Testing!");
fclose($file);
echo "ok";
}
?>
答案 0 :(得分:0)
您可能希望尝试将方法保留在ajax调用中,如下所示:type: 'POST'
。您的Access-Control-Allow-Methods:
ajax-follow.php
下声明了相同的内容