[英]How could I call a c# function using javascript every x seconds?
我有一個將圖像從IPcamera保存到文件流的項目。 我有另一個項目,該文件從文件流中獲取圖像並將其另存為jpg,然后在網絡表單中顯示該圖像。 我添加了一個JavaScript腳本,每隔x秒刷新一次圖像,但是問題是,只有在頁面加載時才會保存新圖像。 這樣做是因為我將c#代碼放入“ Page_Load()”函數中。 我想知道是否有一種方法可以在C#中創建具有保存圖像部分代碼的函數,然后在刷新圖像時每x秒調用一次該函數? 因為現在由於沒有新圖像被保存,因此僅刷新為同一圖像。 我編寫了一個代碼,每隔x秒刷新一次整個頁面,但是我覺得這種方式會更好。 我正在使用Visual Studio 2010。
這是提到的第二個項目的C#代碼:
namespace PlayVideo
public partial class Video : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string saveTo = @"place to save";
FileStream writeStream = new FileStream(saveTo, FileMode.Create, FileAccess.ReadWrite);
using (FileStream fs = File.Open(@"Place where file is saved", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
ReadWriteStream(fs, writeStream);
}
Response.Clear();
Response.TransmitFile("~/images/test.jpg");
}
// readStream is the stream you need to read
// writeStream is the stream you want to write to
private void ReadWriteStream(Stream readStream, Stream writeStream)
{
int Length = 256;
Byte [] buffer = new Byte[Length];
int bytesRead = readStream.Read(buffer,0,Length);
// write the required bytes
while( bytesRead > 0 )
{
writeStream.Write(buffer,0,bytesRead);
bytesRead = readStream.Read(buffer,0,Length);
}
readStream.Close();
writeStream.Close();
}
}
viewer.aspx頁面的代碼為:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="viewer.aspx.cs" Inherits="PlayVideo.viewer" %>
<!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>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div style="height: 60px" id="div1">
<img src="/video.aspx" id="the_image" alt="" /><br />
<script type="text/javascript" language="javascript">
function refreshImage() {
$("#the_image").attr('src', 'video.aspx');
setTimeout(refreshImage, x ms);
}
$(document).ready(function () {
setInterval(refreshImage, x ms);
})
</script>
</div>
</form>
</body>
</html>
有沒有辦法做到這一點? 我已經閱讀了有關客戶端和服務器端的內容,但是由於我已經每隔x秒刷新一次圖像,這有關系嗎?
創建一個使用屬性[WebMethod]標記的公共靜態方法,並使用對該方法的AJAX調用。 示例: 如何使用JQuery Ajax調用從Web方法發送和檢索數據?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.