2012-04-02 79 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