jQuery を使用して Web サイト (フロントエンド) から PHP Zend Server アプリに POST 要求を送信できません。それらは私のサーバー上に個別のアプリとして存在し、2 つの異なるドメインに構成されています。
- サイト.ウェブサイト
- site.server: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 サーバーで次のコードを使用して、public ディレクトリ内の 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] "OPTIONS /login 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 行 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 行 36,リファラー: http://site.website/
クライアントでは、jQuery は .error(request) 関数に分類され、アラートに以下が表示されます。
{"readyState":0,"responseText":"","status":0,"statusText":"error"}