我认为,为了解决您的任务,您可以使用 WebSockets,它支持跨域连接。
在您的情况下,您可以编写聊天客户端并将其放置在客户端的网站上,但来自它的请求将由您的具有数据库访问权限的服务器处理。
延长
当然,您可以将 JSON 与 WebSockets 一起使用,就像 JSON 与 AJAX 一样。WebSockets 是传输 - JSON 是通过此传输传递的内容。
我在研究 WebSockets 时编写了这段代码(聊天侧):
function connect(){
var socket;
var host = window.location.host;
var wsUrl = "ws://" + host + "/connect";
try{
var socket = new WebSocket(wsUrl);
message('<p class="event">Socket Status: '+socket.readyState);
socket.onopen = function(){
message('<p class="event">Socket Status: '+socket.readyState+' (open)');
//Run "Ping-Pong" for support connection
setTimeout(pingPong, 5000);
}
socket.onmessage = function(msg){
//Parse server answer from string to JSON object
var answer = JSON.parse(msg.data);
if (answer.type == 'message') {
message('<p class="message">'+answer.user+': '+answer.message);
}
}
socket.onclose = function(){
message('<p class="event">Socket Status: '+socket.readyState+' (Closed)');
}
} catch(exception){
message('<p>Error'+exception);
}
function send(){
var text = $('#text').val();
if(text==""){
message('<p class="warning">Please enter a message');
return ;
}
try{
//Send data via JSON
socket.send('{"type": "message", "message":'+JSON.stringify(text)+'}');
} catch(exception){
message('<p class="warning">');
}
$('#text').val("");
}
var token = 0;
function pingPong()
{
token++;
try{
var msg = {'type': 'ping', 'token': token};
socket.send(JSON.stringify(msg));
setTimeout(pingPong, 5000);
} catch(exception){
message('<p class="warning">');
}
}
function message(msg){
$('#chatLog').append(msg+'</p>');
}//End message()
$('#text').keypress(function(event) {
if (event.keyCode == '13') {
send();
}
});
$('#disconnect').click(function(){
socket.close();
});
}
$(document).ready(function() {
if(!("WebSocket" in window)){
$('#chatLog, input, button, #examples').fadeOut("fast");
$('<p>Oh no, you need a browser that supports WebSockets. How about <a href="http://www.google.com/chrome">Google Chrome</a>?</p>').appendTo('#container');
}else{
//The user has WebSockets
connect();
}
});
</script>
<meta charset=utf-8 />
<style type="text/css">
body{font-family:Arial, Helvetica, sans-serif;}
#container{
border:5px solid grey;
width:800px;
margin:0 auto;
padding:10px;
}
#chatLog{
padding:5px;
border:1px solid black;
}
#chatLog p{margin:0;}
.event{color:#999;}
.warning{
font-weight:bold;
color:#CCC;
}
</style>
<title>WebSockets Client</title>
</head>
<body>
<div id="wrapper">
<div id="container">
<h1>WebSockets Client</h1>
<div id="chatLog">
</div>
<p id="examples">e.g. try 'hi', 'name', 'age', 'today'</p>
<input id="text" type="text" />
<button id="disconnect">Disconnect</button>
</div>
</div>
</body>
</html>
您也可以使用 SocketIO 库,但我不确定它是否可以跨域工作。