我尝试将2个值从HTML表单传递到javascript函数,使用按钮和Onclick =" myfunction(value1,value2)"。 到目前为止,我没有运气。
您可以在此处查看网站和源代码:View Page
这是我的代码:
Javascript - Ajax Call:
<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>
有没有标准的方法来做到这一点? 我离开了标记吗?
感谢您的帮助!
答案 0 :(得分:2)
您正在传递字符串文字"name"
和"email"
,而不是相应的值。
除非您打算从同一页面内的多个位置调用验证函数,否则您只需将值读入函数本身内的变量,并且不使用任何参数:
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 :(得分:1)
您需要获取要发送的字段的值,收集这些字段并将其传递给您的函数。
<button class="btn btn-primary" Onclick="verification_email(document.getElementById('name').value,document.getElementById('email').value)">Request Verifcation Code</button>
还有其他 - 非最佳做法 - 收集此类信息的方式,例如:
this.form.name.value
this.form.email.vlaue