我正在嘗試爲在線聊天創建自己的JavaScript API。這個API旨在獲得CSS文件和JavaScript文件,並且在加載網站之後,它必須創建一個對話窗口。我想爲其他用戶分享此API。如何通過jquery ajax創建cookie或會話?
例如如果我的域名是mydomain.com,並且在html代碼中包含我的javascript API,它從example.com下載css文件和javascript文件,那麼在用戶端創建cookie或會話的最佳做法是什麼?
下面是我的API:
<div id="fb-dialog"></div>
<script async defer src="http://coders.localhost/api/fb-dialog.js">
var apiConf = {
key: 'YOUR_API_KEY',
language: {
/* Your language codes and default greeting */
"pl" : "Dzień dobry, jestem online. W czym mogę pomóc?",
"en" : "Hello, I'm online. How can I help you?"
}
}
</script>
我想分享這個聊天,但任何對話必須在我的服務器上保存。 我想使用一個數據庫,該數據庫將在其上安裝API的網站ID。在使用Cookie開始對話之前,我需要獲取網站ID,以便我可以返回回覆。我該怎麼辦?
我的javascript:
<script>
$.ajax({
xhrFields: {
withCredentials: true
},
type: "GET",
url: "http://coders.localhost/modules/fb-dialog/heading.php"
}).done(function (data) {
alert("OK");
});
</script>
我的PHP腳本:
<?php
if (!isset($_SERVER['HTTP_ORIGIN'])) {
// This is not cross-domain request
exit;
}
$wildcard = false; // Set $wildcard to TRUE if you do not plan to check or limit the domains
$credentials = true; // Set $credentials to TRUE if expects credential requests (Cookies, Authentication, SSL certificates)
$allowedOrigins = array('http://firma.localhost', 'http://jsfiddle.net');
if (!in_array($_SERVER['HTTP_ORIGIN'], $allowedOrigins) && !$wildcard) {
// Origin is not allowed
exit;
}
$origin = $wildcard && !$credentials ? '*' : $_SERVER['HTTP_ORIGIN'];
header("Access-Control-Allow-Origin: " . $origin);
if ($credentials) {
header("Access-Control-Allow-Credentials: true");
}
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Origin");
header('P3P: CP="CAO PSA OUR"'); // Makes IE to support cookies
// Handling the Preflight
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
exit;
}
if(!isset($_COOKIE['fb-dialog'])) {
setcookie("fb-dialog", "true", time()+3600, "/");
}else{
if(!isset($_POST['data'])) {
if($_COOKIE['fb-dialog'] == 'true') {
setcookie('fb-dialog', 'false', 0, '/');
} else {
setcookie("fb-dialog", "true", time()+3600, "/");
}
}
}
// Response
header("Content-Type: application/json; charset=utf-8");
echo json_encode(array('status' => 'OK'));
?>
上面的代碼工作。我得到一個狀態200,但一個cookie是不是合適的領域,因爲腳本創建域coders.localhost
一個cookie我有兩個領域:
http://firma.localhost - 這是我的網站
http://coders.localhost - 這是我從誰獲得的遠程域名API
我想要通過coders.localhost域爲firma.localhost創建cookie。
你要我用這並沒有什麼用'在請求 – charlietfl
withCredentials'頭 – SeaDog