[英]Obtain All Values from Input Fields Having Same Class and Send to a Script via an AJAX Call
I have a form with the following input fields: 我有一个包含以下输入字段的表单:
<input type="text" class="date" name="date[]" onkeyup="showHint()" />
<input type="text" class="date" name="date[]" onkeyup="showHint()" />
<input type="text" class="date" name="date[]" onkeyup="showHint()" />
Then I have the following JS function: 然后,我有以下JS函数:
function showHint()
{
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)
{
//GET JSON from Validation.php and extract the nodes
var response = xmlhttp.responseText;
var parseJson = JSON.parse(response);
var resultCode = parseJson.code;
var resultMessage = parseJson.message;
var DoB = [];
$(".date").each(function(){
DoB.push($(this).val());
});
var newDob = DoB.slice(0,-1);
}
}
xmlhttp.open("GET","/validation.php?q="+newDob,true);
xmlhttp.send();
}
But I'm getting the following error: 但我收到以下错误:
myfile.js:352 Uncaught ReferenceError: newDob is not defined
at showHint (myfile.js:352)
at HTMLInputElement.onkeyup (VM3224 :618)
showHint @ myfile.js:352
onkeyup @ VM3224 :618
What I'm trying to do is to obtain all the fields of class 'date' and send them - delimited to an external script. 我想做的是获取类'date'的所有字段并将其发送-分隔到一个外部脚本。
try to use jQuery built in serializer 尝试使用序列化器内置的jQuery
console.log($('form').serialize()) // in your submit function
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <input type="text" class="date" name="date[]" onkeyup="showHint()" /> <input type="text" class="date" name="date[]" onkeyup="showHint()" /> <input type="text" class="date" name="date[]" onkeyup="showHint()" /> </form>
regarding you method you have scoping issue check the following code 关于您的方法有范围问题,请检查以下代码
function showHint()
{
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)
{
//GET JSON from Validation.php and extract the nodes
var response = xmlhttp.responseText;
var parseJson = JSON.parse(response);
var resultCode = parseJson.code;
var resultMessage = parseJson.message;
}
}
var DoB = [];
$(".date").each(function(){
DoB.push($(this).val());
});
var newDob = DoB.slice(0,-1);
xmlhttp.open("GET","/validation.php?q="+newDob,true);
xmlhttp.send();
}
you can't define a variable inside onreadystatechange
event because it will not be available in the moment you call open
method 您无法在onreadystatechange
事件中定义变量,因为在您调用open
方法时该变量将不可用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.