javascript 如何根据会话变量以编程方式更改表单操作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9465121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 06:45:25  来源:igfitidea点击:

How to change the form action programatically according to session variable?

c#javascriptjqueryasp.netforms

提问by Anyname Donotcare

If i have a formwhich actionshould differ according to some session variable . How can i change the action of the form dynamically so that on client click of specific link button i could submit the form with the required action.

如果我有一个应该根据某些会话变量formaction有所不同。如何动态更改表单的操作,以便在客户端单击特定链接按钮时,我可以提交具有所需操作的表单。



<form id="myform" action="I wanna to change it dynamically" method="post" > 
    <%-------------%> 
</form>


<script type="text/javascript">
    function submitform()
    {
      document.myform.submit();
    }

</script>


For example :

例如 :

If session["emp"] = 1 then the action is /A.aspx

If session["emp"] = 2 then the action is /B.aspx

回答by James Hill

Option 1

选项1

I typically place server values in hidden fields when the form loads so that I can interact with them in JavaScript:

我通常在表单加载时将服务器值放在隐藏字段中,以便我可以在 JavaScript 中与它们交互:

function submitform()
{
    // Get URL that was set server-side for form submission
    var myHiddenObj = document.getElementById("<%= hdnServerValue.ClientID %>");

    // Get form object
    var myFormObj = document.getElementById("myform");

    // Change form action & submit
    myFormObj.action = myHiddenObj.value;
    myHiddenObj.submit();
}

Option 2

选项 2

If you simply want the form action to change and require no other client-side processing, simply change the form action on the server (you'll need to add runat="server"to your form tag):

如果您只想更改表单操作并且不需要其他客户端处理,只需更改服务器上的表单操作(您需要添加runat="server"到您的表单标签):

Markup:

标记:

<form id="myform" runat="server" action="" method="post" > 
    <%-------------%> 
</form>

C# (or your preferred server side language)

C#(或您首选的服务器端语言)

if(Session["emp"].ToString() == "1")
    myform.Action = "A.aspx";
else if (Session["emp"].ToString() == "2")
    myform.Action = "B.aspx";
else
    // Handle neither 1 or 2

回答by davit_gri

Try this

试试这个

if(condiotion1)
  form1.Attributes.Add("action", "My Action1");
else if(condiotion2)
  form1.Attributes.Add("action", "My Action2");