假设我在客户端(JavaScript)有一个特定的变量:
var isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i);
},
BlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS: function() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
Opera: function() {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function() {
return navigator.userAgent.match(/IEMobile/i);
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
}
};
我想根据 isMobile(在客户端)是真还是假在服务器端做一个条件(if-else)语句。换句话说,我想知道如何从该 JavaScript 文件中获取我的变量并以某种方式将其发送到后面的代码。
我在考虑在服务器端,这将是一些简单的事情:
<---------------Server Side Code (C#)---------------------->
if (isMobile == false)
{
Console.WriteLine("This isnt Mobile");
Console.ReadLine();
V = BLUE;
}
else
{
Console.WriteLine("This IS Mobile");
Console.ReadLine();
V = RED;
<---------------End Server Side Code (C#)---------------------->
/*(RED 和 BLUE 只是我在实际代码中使用的一些随机变量,但并未真正在此处解决,因为我认为这是微不足道的。它们可以是
忽略...) */}
但我不确定如何引用它或将客户端数据发送到服务器端。
我见过或尝试过但没有成功的事情:
我读过类似的示例,但它们涉及像这样引用的函数:Page.ClientScript.RegisterStartupScript(this.GetType(), "~/myScriptPage.js", "myFunction();", 真);
我也见过这样的事情:var x = HttpContext.Current.Session["Variable"]; 起初这似乎可行,但我想我真的不明白如何在我的情况下使用它。
我还阅读了有关使用 ajax 的内容,并且在不向服务器发送 HTTP 请求的情况下无法真正在客户端和服务器端之间进行交互,还有带有隐藏字段的示例。
有没有办法使用上面的代码来做到这一点?这有什么意义吗?任何帮助都会很棒。谢谢。
请您参考如下方法:
您可以使用以下 C# 代码获取用户代理:
System.Web.HttpContext.Current.Request.UserAgent
您可以使用以下方法进行正则表达式测试:
System.Text.RegularExpressions.Regex.IsMatch()
