2012-04-02 77 views
0

使用http://en.allexperts.com/q/Javascript-1520/create-form-submit-fly.htm作为参考,我创建了以下表单,它可以通过onclick事件或任何其他用户事件提交?有没有办法执行此页面加载时,或者我必须始终等待用户事件?表单填写并提交而无需等待事件?

<script> 
var params = something 
//helper function to create the form 
function getNewSubmitForm(){ 
    var submitForm = document.createElement("FORM"); 
    document.body.appendChild(submitForm); 
    submitForm.method = "POST"; 
    return submitForm; 
} 

//helper function to add elements to the form 
function createNewFormElement(inputForm, elementName, elementValue){ 
    var newElement = document.createElement("<input name='"+elementName+"' type='hidden'>"); 
    inputForm.appendChild(newElement); 
    newElement.value = elementValue; 
    return newElement; 
} 
function createFormAndSubmit(){ 
    var submitForm = getNewSubmitForm(); 
    createNewFormElement(submitForm, "field1", params.data1); 
    createNewFormElement(submitForm, "field2", params.data2); 
    submitForm.name= "submitpost"; 
    submitForm.action= "some URL"; 
    submitForm.submit(); 
} 
</script> 
+0

我有它通过硬编码使用document.write然后填充值工作,但这一决议将是很好,可能帮助别人......版主的欢迎,如果他们认为,要删除这个帖子更好的选择... – BAU 2012-04-02 11:32:55

回答

0

如果我理解正确,你想要做下面的事情。对?

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script> 
    <script type="text/javascript"> 

    $(document).ready(function(){ 
     var params = ["1","7"]; 
     createFormAndSubmit(); 

     //helper function to create the form 
     function getNewSubmitForm(){ 
      var submitForm = document.createElement("FORM"); 
      document.body.appendChild(submitForm); 
      submitForm.method = "POST"; 
      return submitForm; 
     } 

     //helper function to add elements to the form 
     function createNewFormElement(inputForm, elementName, elementValue){ 
      var newElement = document.createElement("INPUT"); 
      newElement.name = elementName; 
      newElement.type = 'hidden'; 
      newElement.value = elementValue; 
      inputForm.appendChild(newElement); 
      return newElement; 
     } 

     function createFormAndSubmit(){ 
      var submitForm = getNewSubmitForm(); 
      createNewFormElement(submitForm, "field1", params[0]); 
      createNewFormElement(submitForm, "field2", params[1]); 
      submitForm.name= "submitpost"; 
      submitForm.action= "show.jsp"; 
      submitForm.submit(); 
     } 

    }); 
    </script> 
+0

我不知道为什么,但似乎并不奏效。我认为它应该!但它不......我曾尝试过:D显然你不得不等待用户事件。 – BAU 2012-04-04 10:46:31

+0

真的吗?对我来说,这工作没有等待一些用户事件。在加载包含此代码的页面时,表单会立即提交,并在另一个页面show.jsp中看到结果。你的情况会怎样? – 2012-04-04 11:10:07