我构建了一个简单的环聊应用程序,当有人从我的网页(在Google plus之外)启动环聊时,它会通知我。
我正处于调用服务器端脚本的阶段,该脚本通知我新用户发起了环聊,我需要将消息传递回环聊以向用户显示更新的提示。类似于 - 支持工程师已收到有关此环聊的警报,并将很快与您联系。
我已经阅读了环聊数据,包括谁从环聊 API 加入并将其传递给我的服务器端代码没有问题。但我不确定如何通过 ajax 请求将信息传回我的环聊应用程序。
这是我使用 jQuery 的 ajax 请求。
var hangoutUrl = gapi.hangout.getHangoutUrl();
var personsInHangout = gapi.hangout.getParticipants();
var callbackUrl = 'http://styxofdynamite.bitnamiapp.com/notify.php?';
$.ajax({
url: callbackUrl,
dataType: 'text',
data: {
"personsInHangout" : personsInHangout,
"hangoutUrl" : hangoutUrl,
"topic" : params['gd'],
}
}).done( function(data, status, xhr){
//call was made process result
$('.msg').html(data.msg);
}).fail( function(xhr, status, error){
$('.msg').html("There was a problem contacting the server. (" + status + ")");
});
目前我没有返回任何东西,所以我很高兴地打.fail()
理想情况下我需要从 notify.php 返回一些东西回到这个环聊应用程序。
服务器侧片段:
$personsInHangout = $_GET['personsInHangout'];
$hangoutUrl = $_GET['hangoutUrl'];
$topic = $_GET['topic'];
$emailMessage = 'Hey Support Team, ';
for($i = 0, $size = count($personsInHangout); $i < $size; ++$i) {
$emailMessage .= $personsInHangout[$i]['person']['displayName'];
$emailMessage .= ' is currently waiting in the support ';
$emailMessage .= '<a href="'.$hangoutUrl.'">hangout</a>';
$emailMessage .= ' to discuss ' . $topic;
}
print $emailMessage;
$to = 'support@team.com';
$subject = 'New Hangout Request';
$headers = 'From: hangout.monitor@team.com' . "'r'n" .
'Reply-To: hangout.monitor@team.com' . "'r'n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $emailMessage, $headers);
//return something to say that a support engineer has been notified.
使用 php 内置的 json_encode
文档发回 JSON 格式的响应。 除了数据之外,您还需要发送一些标头。
<?php
// This tells the browser the following data should be interpreted as JSON, as opposed to text or html
header('Content-Type: application/json');
// Take any $data and format it correctly as JSON. Works with arrays, strings, numbers
echo json_encode($data);
?>
如果你想
将json与jQuery和PHP一起使用,你需要做1件事:
首先,您需要在 PHP 中发送一个 json 响应:
通知.php
<?php
// your code, send mail, etc.
header('Content-Type: application/json');
die(json_encode(array(
'foo' => 'bar',
)));
然后,您有一个声明,即您在客户端中接收 json 数据,并使用 dataType 选项。
您的客户端 :
$.ajax({
url: callbackUrl,
dataType: 'json',
data: {
"personsInHangout" : personsInHangout,
"hangoutUrl" : hangoutUrl,
"topic" : params['gd'],
},
success: function(data){
console.log(data.foo); // Will display "bar" in debug console
}
})
我也有问题。您的"回拨"网址是"http"。这是被谷歌的规则阻止的。你必须使用"https"。
var callbackUrl = 'http://styxofdynamite.bitnamiapp.com/notify.php?';
var callbackUrl = 'https://styxofdynamite.bitnamiapp.com/notify.php?';