简体   繁体   English

如何将数据从C#发送到JavaScript / AJAX网页

[英]How to send data from C# to JavaScript/AJAX webpage

Basically, I have a need for ac# server to be able to send data back to an HTML5 webpage which has previously send data to the server. 基本上,我需要ac#服务器能够将数据发送回HTML5网页,而HTML5网页以前已经将数据发送到服务器。 The server is retrieving data from another application and this data then needs to be send to the webpage to be displayed. 服务器正在从另一个应用程序检索数据,然后需要将该数据发送到要显示的网页。

This c# server is running on .NET CF 3.5 so websockets are not an option (not supported). 此C#服务器在.NET CF 3.5上运行,因此无法使用websocket(不支持)。

I have seen some suggestions elsewhere but nothing which fits the necessary criteria for this particular situation. 我在其他地方看到了一些建议,但没有什么适合这种特殊情况的必要标准。 Most other implementations seem to work on the basis that the webpage will only be waiting for this data to be sent over. 大多数其他实现似乎是在网页等待发送此数据的基础上工作的。

Any and all suggestions welcome! 任何建议都欢迎!

If websockets are not an option then you are left with Comet . 如果没有websockets选项,那么您将剩下Comet

Client-side you could do something like this : 在客户端,您可以执行以下操作:

(function poll(){
    $.ajax({ 
        url: "url",
        success: function(data) { /*display data*/ },
        complete: poll, 
        timeout: 30000 });
})();

Which means an ajax request will be sent every 30 seconds. 这意味着ajax请求将每30秒发送一次。

This is not as performant as websockets but it works quite well. 它的性能不如websockets,但效果很好。

  1. Create an .aspx page and remove all the HTML from it. 创建一个.aspx页并从中删除所有HTML。 Call it GetData.aspx 称之为GetData.aspx
  2. In the code behind of GetData.aspx.cs you can receive the POST data from the HTML5 page. 在GetData.aspx.cs后面的代码中,您可以从HTML5页面接收POST数据。
  3. Do work. 做工作。

  4. Use jquery. 使用jQuery。

  5. $.post("GetData.aspx",{name: value},function(json){ // put processing instructions here. }); $ .post(“ GetData.aspx”,{name:value},function(json){//将处理指令放在此处。});

There are two ways to do this : 有两种方法可以做到这一点 :

Using a ASP.NET web-page 使用ASP.NET网页

  1. Create HTML element that calls a javascript function 创建调用javascript函数的HTML元素
  2. Inside of the javascript function, use ajax to make a POST to a ASP.NET Web Page (that uses C# as back-end) 在javascript函数内部,使用Ajax对ASP.NET网页 (使用C#作为后端)进行POST。
  3. Get the returned value in the ajax "success" block. 在ajax“成功”块中获取返回值。
  4. Use as you wish... 随便使用...

Using a jSON string return 使用jSON字符串返回

  1. Create HTML element that calls a javascript function 创建调用javascript函数的HTML元素
  2. Inside of the javascript function, use ajax to make a POST to a Web Service (that uses C# as back-end), that returns a jSON string. 在javascript函数内部,使用ajax对Web服务 (使用C#作为后端)进行POST,以返回jSON字符串。
  3. Use the returned jSON data in which ever way needed. 按需要使用返回的jSON数据。

I personally prefer jSON, as it emulates a data set, and works well with HTML and ajax. 我个人更喜欢jSON,因为它可以模拟数据集,并且可以很好地与HTML和ajax一起使用。

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

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