在javascript中通过函数发送POST

时间:2011-12-03 06:20:39

标签: javascript

如果验证通过,我正在使用以下代码发送POST请求。但事实并非如此。有人能告诉我一件事,让它发挥作用。

<script type="text/javascript">

    function go()
    {
    var username = document.form.name.value;
    var pwd = document.form.pwd.value;
    if (username == '') {
      var oldHTML = document.getElementById('myAnchor').innerHTML="Please fill out username.";
    var newHTML = "<span style='color:red'>" + oldHTML + "</span>";
    document.getElementById('myAnchor').innerHTML = newHTML;
    }
    if (pwd == '') {
      var oldHTML = document.getElementById('myAnchor2').innerHTML="Please fill out password.";
    var newHTML = "<span style='color:red'>" + oldHTML + "</span>";
    document.getElementById('myAnchor2').innerHTML = newHTML;
    }
      else {
       document.form.method="POST";
       document.form.action = "data.php";
    }
    </script>

2 个答案:

答案 0 :(得分:1)

一切看起来都很正确,你只需要提交表格即可。将以下行添加到else块中,如下所示:

else {
    document.form.method="POST";
    document.form.action = "data.php";
    //submit the form -- new line is below
    document.form.submit();
    }

答案 1 :(得分:0)

下面是如何通过javascript提交表单的代码段

<form name="myform" action="handle-data.php">
Search: <input type='text' name='query' />
<a href="javascript: submitform()">Search</a>
</form>
<script type="text/javascript">
function submitform()
{
  document.myform.submit();
}
</script>