简体   繁体   中英

Post request with ajax for Firebase Cloud Messaging

I have writtent this script to send notification from my HTML page. When i try to send the request, i get both messages "Success" and "Fail" and the notification is not sent. I call the function get_data_for_notification() on button click.

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
  <script type="text/javascript">
    function get_data_for_notification(){
        var title = document.getElementById('news_title').value;
        var subtitle = document.getElementById('news_small_description').value;

        $.ajax({
                 type : 'POST',
                 url : "https://fcm.googleapis.com/fcm/send",
                 headers : {
                     Authorization : 'key=mykey'
                 },
                 contentType : 'application/json',
                 dataType: 'json',
                 data: JSON.stringify({"to": "/topics/android",  "priority" : "high", "notification": {"title":title,"body":subtitle}}),
                 success : alert("Success")            ,
                 error : alert("Fail")
             }) ;
    }
  </script>

Your script executes, before sending the request, alert("Success") and alert("Fail") and assigns their return value as the event handlers.

You have to wrap them in an anonymous function:

    $.ajax({
        type: 'POST',
        url: "https://fcm.googleapis.com/fcm/send",
        headers: {
            Authorization: 'key=mykey'
        },
        contentType: 'application/json',
        dataType: 'json',
        data: JSON.stringify({
            "to": "/topics/android",
            "priority": "high",
            "notification": {
                "title": title,
                "body": subtitle
            }
        }),
        success: function(responseData) {
            alert("Success");
        }
        error: function(jqXhr, textStatus, errorThrown) {
            /*alert("Fail");*/   // alerting "Fail" isn't useful in case of an error...
            alert("Status: " + textStatus + "\nError: " + errorThrown);
        }
    });

问题出在按钮类型上,我需要使用type="button"而不是type="submit"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM