如何在Seprate .Js文件中访问我的服务器端变量 [英] How Do I Access My Server Side Variable In Seprate .Js File
本文介绍了如何在Seprate .Js文件中访问我的服务器端变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
aspx:
string name =something;
i需要访问此值单独的.js文件
aspx:
string name ="something";
i need to access this value in separate .js file
推荐答案
尝试(在你的脚本中)
var mJSVariable =<%:myServerSideVariable% > ;;
Try (in your script)
var mJSVariable = <%:myServerSideVariable%>;
按照以下流程完成:
第1步:在代码隐藏文件中将变量声明为public和static
Follow below process to accomplish:
Step 1: Declare variable as public and static in code-behind file
public partial class Page1 : System.Web.UI
{
public string firstName = "Manas";
protected void Page_Load()
{
// Your logic
}
}
第2步:访问js文件中的变量:
Step 2: Access the variable in js file:
<script>
GetMyName();
function GetMyName()
{
alert(<%=this.firstName%>);
}
</script>
编辑(另一种方式):
Edit(Another way):
public partial class Page1 : System.Web.UI
{
public string firstName = "Manas";
protected void Page_Load()
{
// Your logic
string script = string.Format("var firstName = '{0}';", "Manas");
if (!ClientScript.IsClientScriptBlockRegistered("myScript"))
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "myScript", script, true);
}
}
}
在temp.js文件中添加代码
Add code in temp.js file
<script>
GetMyName();
function GetMyName()
{
alert(firstName);
}
</script>
这篇关于如何在Seprate .Js文件中访问我的服务器端变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文