2015-06-20 45 views
0

我想通過一個按鈕和Onclick =「myfunction(value1,value2)」將2個值從HTML表單傳遞到javascript函數。 到目前爲止,我沒有運氣。從HTML表單傳遞多個字符串到JavaScript函數?

您可以查看該網站的源代碼在這裏:View Page

這裏是我的代碼:

使用Javascript - AJAX調用:

<script type="text/javascript"> 
function verification_email(name,email) { 

    var xmlhttp; 
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari 
     xmlhttp=new XMLHttpRequest(); 
    } 
    else {// code for IE6, IE5 
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    xmlhttp.onreadystatechange=function() { 
     if (xmlhttp.readyState==4 && xmlhttp.status==200) { 
     document.getElementById("result").innerHTML=xmlhttp.responseText; 
     } 
    } 

    xmlhttp.open("POST","send_verification_email.php?",true); 
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); 
    xmlhttp.send("name="+name+"++email="+email); 

} 
</script> 

HTML表單:

  <h3 class="subtitle">Verification Details:</h3> 
      <p><input type="text" class="form-control" placeholder="First Name" id="name" /></p> 
      <p><input type="text" class="form-control" placeholder="Email Address" id="email"/></p> 

      <p><button class="btn btn-primary" Onclick="verification_email('name','email')">Request Verifcation Code</button></p> 

</form> 

有沒有一個標準的方法來做到這一點? 我的方式離譜嗎?

感謝您的幫助!

+1

如果我們不知道自己在做什麼,我們該如何幫助您?請發佈您的代碼。 –

+0

我試圖把它全寫在我的手機上,它幾乎是不可能的,所以我去抓住舊筆記本電腦來添加代碼。我希望現在更有意義。 –

+1

那麼,你真的將字符串「name」和「email」傳遞給函數,而不是相應字段的值。所以我猜你的實際問題是*「如何獲得按名稱輸入的值」*? –

回答

2

除非你打算調用在同一頁面中的多個位置的驗證功能,你可以簡單地讀值到函數本身內部的變量,並使用無參數的責任:

HTML

<p><button class="btn btn-primary" onclick="verification_email()">Request Verifcation Code</button></p> 

JS

function verification_email() { 
    var name = document.getElementById('name').value; 
    var email = document.getElementById('email').value; 
    var xmlhttp; 
    etc... 
1

您需要獲取要發送的字段的值,收集這些值並將它們傳遞給您的函數。

<button class="btn btn-primary" Onclick="verification_email(document.getElementById('name').value,document.getElementById('email').value)">Request Verifcation Code</button> 

還有其他 - 非最佳實踐 - 收集這些信息的方式,如:你傳入字符串文字"name""email"而不是適當的值

this.form.name.value  
this.form.email.vlaue 
相關問題