我无法使用 jQuery 从我的网站(前端)向我的 PHP Zend Server 应用程序发送 POST 请求。它们在我的服务器上作为单独的应用程序存在,并配置为在两个不同的域上:
- 网站.网站
- 站点服务器:8899
最奇怪的是,它起作用了,我什么都没改变(我想!),现在它不起作用......所以我希望有人能帮忙。
我正在使用以下 JavaScript 发出 POST 请求:
var login = function(email, password) {
var requestPath = serverPath + "/login";
var params = {
email : email,
password : password
};
$.post(requestPath, params).done(function(response) {
console.log(JSON.stringify(response));
if(isResponseError(response)) {
alert(response.opStatus + ': "' + response.opMessage + '"');
} else {
window.localStorage.setItem("zobyAuthData", JSON.stringify(response));
if(window.localStorage.getItem("zobyAuthData") !== null) {
window.location = 'home.php';
}
}
}).error(function(request) {
console.log(JSON.stringify(request));
alert(JSON.stringify(request));
});
};
我在我的 Zend 服务器上使用以下代码在公共目录中的 index.php 文件中启用 CORS:
function EnableCors() {
// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
echo "You have CORS!";
}
当我尝试发出 POST 请求时,我还检查了 Apache access_log 和 error_log 文件,并将以下行写入 access_log:
127.0.0.1 - - [29/Jul/2013:12:00:37 +0100]“选项/登录 HTTP/1.1”200 -
127.0.0.1 - - [29/Jul/2013:12:01:04 +0100] “POST/HTTP/1.1”200 6611
error_log 有:
[Mon Jul 29 11:47:36 2013] [error] [client 127.0.0.1] PHP Notice: Undefined index: email in /Library/WebServer/Documents/Site/WebsiteServer/application/controllers/LoginController.php on line 35,推荐人:http : //site.website/
[Mon Jul 29 11:47:36 2013] [error] [client 127.0.0.1] PHP Notice: Undefined index: password in /Library/WebServer/Documents/Site/WebsiteServer/application/controllers/LoginController.php on line 36,推荐人:http : //site.website/
在客户端,jQuery 属于 .error(request) 函数,并在警报中显示以下内容:
{"readyState":0,"responseText":"","status":0,"statusText":"error"}