2012-03-07 120 views

回答

5

您可以從另一個表格調用提交方法,並使用callapplythis進行破解。

document.createElement('form').submit.call(myForm); 

...但它不會在IE6上工作。

將輸入重命名爲提交以外的內容比較安全。

+0

有沒有一種方法,使其工作在IE6呢? – 2012-03-07 12:34:12

+0

嗯。它會工作,如果表單將被添加到DOM? – kirilloid 2012-03-07 12:34:20

+0

+1好玩的做法。 – Sarfraz 2012-03-07 12:34:30

0

我認爲單詞「submit」是一個保留字,不能用於除type=submit元素之外的任何輸入元素。

但總有辦法打破規則。 通過使用AJAX執行POST請求,您可以使用任何你想要的名字。 而且你甚至不需要輸入元素的名稱,只是一個id。事實上,你甚至不需要一個表單,只是一個輸入元素。

<html> 
<head> 
<script type="text/javascript"> 
function ajaxRequest() 
{ 
var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] 
if(window.ActiveXObject) 
{ 
    for(var i=0; i<activexmodes.length; i++) 
    { 
    try{return new ActiveXObject(activexmodes[i])} 
    catch(e){} 
    } 
    } 
else if(window.XMLHttpRequest) // if Mozilla, Safari etc 
    return new XMLHttpRequest() 
else 
    return false 
} 

function myfunc() 
{ 
var mypostrequest=new ajaxRequest() 
mypostrequest.onreadystatechange=function() 
{ 
    if(mypostrequest.readyState==4) 
    { 
    if(mypostrequest.status==200 || window.location.href.indexOf("http")==-1) 
    { 
    document.getElementById("result").innerHTML=mypostrequest.responseText 
    } 
    } 
    } 
var hiddenValue=encodeURIComponent(document.getElementById("submit").value) 
var parameters="submit="+hiddenValue 
mypostrequest.open("POST", "go2.php", true) 
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded") 
mypostrequest.send(parameters) 
} 
window.onload = myfunc; 
</script> 
</head> 
<body> 
<div id="result"></div> 
<input type='hidden' id='submit' value='1'> 
</body> 
</html> 
0

您可以在提交按鈕上使用.click()函數。如果沒有提交按鈕,您將不得不首先將其中一個插入DOM。

像這樣:

var submitbutton = document.createElement('input'); 
submitbutton.type = "submit"; 
document.getElementById("yourForm").appendChild(submitbutton); 
submitbutton.click(); 

或者,如果你有一個提交按鈕:

document.getElementById("yourButton").click()