urban airship - sending Broadcast message using Js

2019-09-19 23:55发布

I'm trying to send a broadcast message using a std. html/javascript to Android devices. I have found a script here on stackoverflow but i can't get it to work. it returns no errors. Then a send a message from urban airship admin i works fine. Is i missing something here??

<script language="JavaScript1.2" type="text/javascript">

var ruleObj = {
    "android": {"alert": "test"}
}
;

var objStr = JSON.stringify(ruleObj);
// username : Application Key;
// password : Application Master Secret;

    jQuery(document).ready(function(jQuery){ 

        jQuery.ajax({
        type: "POST",
        contentType:"application/json",
        username: "qE.........",
        password: "zp........",
        url:"https://go.urbanairship.com/api/push/broadcast/",
        data: objStr,
        success: function(data){
                            alert(data);
            }
        });

    });

</script>

2条回答
乱世女痞
2楼-- · 2019-09-20 00:11

If the remote server doesn't add an Access-Control-Allow-Origin header the AJAX call will then fail the "same origin policy", and the query will be denied.

The normal way around this is to modify your URL so jQuery will attempt to use JSONP instead of plain JSON.

You can do this in two ways:

url: "https://go.urbanairship.com/api/push/broadcast/?callback=?"

or by adding:

dataType: 'jsonp'
查看更多
干净又极端
3楼-- · 2019-09-20 00:12

In addition to using

dataType: "jsonp",

You will also want to use the statusCode parameter. Since you will not be getting valid JSON back, you need to instead check the status code that is passed back to determine if you call was a success:

statusCode: {
    200: function() {
        alert('message sent!');
    },
    500: function(  ) {
        alert('500 error');
    }
}
查看更多
登录 后发表回答