如何使用XHR(Ajax)发送推送通知请求

时间:2016-01-16 08:12:39

标签: android jquery ajax curl

这是使用cURL从终端发出请求的命令。有用!但是,我不知道如何通过XHR(Ajax)发出相同的请求。任何帮助将不胜感激。

curl --header "Authorization: key=ABC123" --header "Content-Type: application/json" https://android.googleapis.com/gcm/send -d "{\"registration\_ids\":[\"DFG456\"]}"

1 个答案:

答案 0 :(得分:1)

这是PHP代码(您需要安装php5-curl包):

// curl.php
$data = ["registration_ids" => ["DFG456"]];
$dataString = json_encode($data);

$curl = curl_init('https://android.googleapis.com/gcm/send');
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: key=ABC123',
    'Content-Length: ' . strlen($dataString)
]);

$result = curl_exec($curl);
print_r($result);

和ajax请求(使用jquery):

// index.html
<button id="send">Send</button>
<script>
    $("#send").click(function() {
        $.get("curl.php", function(data) {
            console.log(data);
        });
    });
</script>
相关问题