简体   繁体   English

使用javascript将通知推送到wp8(JQuery请求)

[英]Push notification to wp8 using javascript (JQuery Request)

So what I am trying to do is pushing notifications to windows 8 application using javascript. 所以我想做的就是使用JavaScript将通知推送到Windows 8应用程序。

So after checking this website which is the only useful website I found. 因此,在检查了该网站之后,这是我发现的唯一有用的网站。

http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202977(v=vs.105).aspx http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202977(v=vs.105).aspx

I understood the following: 我了解以下内容:

1- You need to develop an app that request push notification service URI which will be then shared with a push client service. 1-您需要开发一个请求推送通知服务URI的应用,然后将其与推送客户端服务共享。

(The code for this app needs nothing as you will simply copy it from the link above) (此应用的代码不需要任何内容​​,因为您只需从上面的链接中复制它即可)

2- You need to send a notification (raw notification) using a push client service 2-您需要使用推送客户端服务发送通知(原始通知)

(here appears the problem :) ) (这里出现问题:))

The issue that the code is for .NET files which I am not familiar with. 该代码是我不熟悉的.NET文件的问题。 I tried to convert the code from the .NET to HTML and .JS where I am going to send ajax request to the given URI. 我试图将代码从.NET转换为HTML和.JS,然后将ajax请求发送到给定的URI。

However this give me a wired error and unfortunately I couldn't find an example of sending notification using .JS 但这给了我一个有线错误,不幸的是我找不到使用.JS发送通知的示例

So here is the original code which basically defines a simple form that will send request to the URI. 因此,这是原始代码,基本上定义了一种简单形式,该形式会将请求发送到URI。 The only difference between this and my code that I am using JQuery Ajax request to send 这和我使用JQuery Ajax请求发送的代码之间的唯一区别

Original Code 原始码

HTML HTML

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SendRaw.aspx.cs" Inherits="SendRaw.SendRaw" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
   <div>

    <br />
    Enter URI:</div>
<asp:TextBox ID="TextBoxUri" runat="server" Width="666px"></asp:TextBox>
<br />
<br />
Enter Value 1:<br />
<asp:TextBox ID="TextBoxValue1" runat="server"></asp:TextBox>
<br />
<br />
Enter Value 2:<br />
<asp:TextBox ID="TextBoxValue2" runat="server"></asp:TextBox>
<br />
<br />
<br />
<asp:Button ID="ButtonSendRaw" runat="server" onclick="ButtonSendRaw_Click" 
    Text="Send Raw Notification" />
<br />
<br />
Response:<br />
<asp:TextBox ID="TextBoxResponse" runat="server" Height="78px" Width="199px"></asp:TextBox>
</form>

C# (.NET) C#(.NET)

 using System.Net;
 using System.IO;
 using System.Text;

C# (.NET) C#(.NET)

protected void ButtonSendRaw_Click(object sender, EventArgs e)
    {
        try
        {
            // Get the URI that the Microsoft Push Notification Service returns to the push client when creating a notification channel.
            // Normally, a web service would listen for URIs coming from the web client and maintain a list of URIs to send
            // notifications out to.
            string subscriptionUri = TextBoxUri.Text.ToString();


            HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(subscriptionUri);

            // Create an HTTPWebRequest that posts the raw notification to the Microsoft Push Notification Service.
            // HTTP POST is the only method allowed to send the notification.
            sendNotificationRequest.Method = "POST";

            // Create the raw message.
            string rawMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
            "<root>" +
                "<Value1>" + TextBoxValue1.Text.ToString() + "<Value1>" +
                "<Value2>" + TextBoxValue2.Text.ToString() + "<Value2>" +
            "</root>";

            // Set the notification payload to send.
            byte[] notificationMessage = Encoding.Default.GetBytes(rawMessage);

            // Set the web request content length.
            sendNotificationRequest.ContentLength = notificationMessage.Length;
            sendNotificationRequest.ContentType = "text/xml";
            sendNotificationRequest.Headers.Add("X-NotificationClass", "3");


            using (Stream requestStream = sendNotificationRequest.GetRequestStream())
            {
                requestStream.Write(notificationMessage, 0, notificationMessage.Length);
            }

            // Send the notification and get the response.
            HttpWebResponse response = (HttpWebResponse)sendNotificationRequest.GetResponse();
            string notificationStatus = response.Headers["X-NotificationStatus"];
            string notificationChannelStatus = response.Headers["X-SubscriptionStatus"];
            string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];

            // Display the response from the Microsoft Push Notification Service.  
            // Normally, error handling code would be here. In the real world, because data connections are not always available,
            // notifications may need to be throttled back if the device cannot be reached.
            TextBoxResponse.Text = notificationStatus + " | " + deviceConnectionStatus + " | " + notificationChannelStatus;
        }
        catch (Exception ex)
        {
            TextBoxResponse.Text = "Exception caught sending update: " + ex.ToString();
        }

MY Code 我的密码

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1">
    <script src="jquery-2.0.3.min.js"></script>

   <script>
     $(document).ready(function(e) {
        $('#ButtonSendRaw').click(function(){
        console.log("Button Pressed");

        var subscriptionUri = $('#TextBoxUri').val();
        var textbox1 = $('#TextBoxValue1').val();
        var textbox2 = $('#TextBoxValue2').val();

        var rawMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
        "<root>" +
            "<Value1>" + textbox1 + "<Value1>" +
            "<Value2>" + textbox2 + "<Value2>" +
        "</root>";
        console.log("Sending Data");
        $.ajax({
            url: subscriptionUri,
            type: "POST",
            data: rawMessage,
            contentType:"text/xml",
            success: function(response) {
               console.log('Sucess');
               console.log("login| Response");
               console.log(response);
              },
             error: function (xhr, ajaxOptions, thrownError) {
                    console.log(xhr.status);
                    console.log(thrownError);
            }

            });
        });
    });


</script>
    </head>
    <body>
    Enter URI:<input type="text" ID="TextBoxUri" Width="666px" /> <br />

Enter Value 1: <input type="text" ID="TextBoxValue1" /> <br />

Enter Value 2: <input ID="TextBoxValue2" /> <br />

<button id="ButtonSendRaw">Sending Data</button> <br />

Response: <input ID="TextBoxResponse" Height="78px" Width="199px" /> <br />

  </body>
  </html>

The error I am getting from this is: 我从中得到的错误是:

    405 (Method Not Allowed)

Where method is set automatically to OPTIONS, although I am sending a POST request 尽管我正在发送POST请求,但方法自动设置为OPTIONS

Any suggestions, thanks in advance :) 任何建议,在此先感谢:)

I'm assuming that the subscriptionuri value is a URI with a different domain than the website that contains your page with the JQuery code. 我假设subscriptionuri值是一个URI,它的域与包含带有JQuery代码的页面的网站的域不同。 (eg your website is hosted on www.mywebsite.com and the subscriptionuri is www.microsoft.com/api/push) (例如,您的网站托管在www.mywebsite.com上, subscriptionuri是www.microsoft.com/api/push)

What happens in this scenario is that the browser will attempt to make a Cross Domain Request. 在这种情况下,浏览器将尝试发出跨域请求。 There are security considerations to keep in mind when using Cross Domain Requests like Cross-Site Request Forgery or Cross-Site Scripting. 使用跨域请求(例如跨站点请求伪造或跨站点脚本)时,需要牢记安全考虑。 See here for more information. 有关更多信息,请参见此处

As a rule, Modern browsers will only allow Ajax calls to uris in the same domain as the HTML page. 通常,现代浏览器仅允许对与HTML页面相同域中的uri的Ajax调用。 If the uri is in other domain, the browser won't make the direct call. 如果uri在其他域中,则浏览器将不会直接调用。 Instead, it will try to make a CORS request. 相反,它将尝试发出CORS请求。

Cross Origin Resource Sharing (CORS) specification provides a mechanism for web application developers to have a browser-supported mechanism to make XmlHttpRequests to another domain in a secure manner. 跨源资源共享(CORS)规范为Web应用程序开发人员提供了一种机制,该机制具有浏览器支持的机制,以安全的方式将XmlHttpRequest发送到另一个域。 The CORS mechanism works by adding HTTP headers to cross-domain HTTP requests and responses. 通过将HTTP标头添加到跨域HTTP请求和响应中,CORS机制起作用。 These headers indicate the origin of the request and the server must indicate via headers in the response whether it will serve resources to this origin. 这些标头指示请求的来源,服务器必须通过响应中的标头指示是否将服务于该来源的资源。 This exchange of headers is what makes CORS a secure mechanism. 头的这种交换使CORS成为一种安全机制。 The server must support CORS and indicate that the domain of the client making the request is permitted to do so. 服务器必须支持CORS,并指出允许发出请求的客户端域可以这样做。 The beauty of this mechanism is that it is automatically handled by the browser and web application developers do not need to concern themselves with its details. 这种机制的优点在于,它是由浏览器自动处理的,Web应用程序开发人员无需担心其细节。

There are different flows in CORS like a Simple Request, Preflighted Requests and Credentialed Requests. CORS中有不同的流程,例如简单请求,预检请求和凭证请求。 The request that you are trying to make will fall in to the category of a Preflighted Request because your request body has a Content-Type other than text/plain, application/x-www-form-urlencoded, or multipart/form-data. 您尝试发出的请求将属于“预检请求”类别,因为您的请求主体具有Content-Type,而不是text / plain,application / x-www-form-urlencoded或multipart / form-data。

OPTIONS http://otherdomain.com/some-resource/ HTTP/1.1
Origin: http://mydomain.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-Foo

This will receive the following response from the server (if CORS is enabled on the Server) indicating that the POST operation is allowed 这将从服务器接收以下响应(如果在服务器上启用了CORS),表明允许POST操作

HTTP/1.1 200 OK
Access-Control-Allow-Origin: http://mydomain.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: X-Foo
Access-Control-Max-Age: 3600

Once this response is received, your browser will then make the actual POST. 收到此响应后,您的浏览器将进行实际的POST。

PUT http://otherdomain.com/some-resource/ HTTP/1.1
Content-Type: application/xml; charset=UTF-8
X-Foo: bar

This process ensures among other things that servers that are not CORS-enabled will not process a request that might modify server resources as a side effect prior to the browser disallowing the response because it lacks the proper Access-Control-Allow-Origin header. 此过程可确保未启用CORS的服务器不会处理可能会修改服务器资源的请求,这是浏览器不允许响应之前的副作用,因为它缺少适当的Access-Control-Allow-Origin标头。

In your case since your Server is not CORS enabled you are seeing a OPTIONS call but not the subsequent POST. 在您的情况下,由于您的服务器未启用CORS,您会看到一个OPTIONS调用,但没有看到后续的POST。 The easiest way to resolve this is to enable CORS on your server so that the necessary headers can be sent by the server in the response. 解决此问题的最简单方法是在服务器上启用CORS,以便服务器可以在响应中发送必要的标头。 Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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