我有这个注册脚本,我使用 AJAX 将输入的数据传送到 php 到 mysql 数据库。一切都工作得很好,“除了”选中的单选按钮的值。它只获取第一个值,而不获取检查的值。是的,我知道还有其他 jQuery 方法没有这个问题,但是尽管我对此很陌生,但表单追加 Ajax 方法最适合上传图像,而这正是我将使用它的目的并且将有许多使用单选按钮的选项以及多重上传图像选项。所以我需要在继续之前完善这个简单的脚本。
我已经搜索了两天了,正确的是使用 formdata.append 行收集单选按钮值数据,无论我如何修改它,它都会使脚本失败。任何帮助和建议或阅读链接都会有帮助,仍在学习,谢谢,
<script>
function _(id){ return document.getElementById(id); }
function submitForm(){
_("mybtn").disabled = true;
_("status").innerHTML = 'please wait ...';
var formdata = new FormData();
formdata.append( "n", _("n").value );
formdata.append( "e", _("e").value );
formdata.append( "gender", _("gender").value );
var ajax = new XMLHttpRequest();
ajax.open( "POST", "register_script.php" );
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
if(ajax.responseText == "success"){
_("my_form").innerHTML = '<p style="margin:1em;background:#E33A29;color:#fff;padding:1em;border-radius:10px;">Thanks '+_("n").value+', you have succeessfully registered !.</p>';
} else {
_("status").innerHTML = ajax.responseText;
_("mybtn").disabled = false;
}
}
}
ajax.send( formdata );
}
</script>
<div class="flex_container">
<div class="card">
<h2>Register</h2>
<form id="my_form" onsubmit="submitForm(); return false;" method="post">
<input id="n" type="text" placeholder="Full Name" required>
<input id="e" type="text" placeholder="Email" required>
<span style="font-size: 18px;margin-top:0.5em;margin-bottom:1em;font-weight: bold;">Gender</span>
<label>
<input id="gender" value="Male" type="radio" name="gender"/>
<span>Male</span>
</label>
<label>
<input id="gender" value="Female" type="radio" name="gender"/>
<span>Female</span>
</label>
<label>
<input id="gender" value="Other" type="radio" name="gender"/>
<span>Other</span>
</label><br>
<p><span id="status"></span></p>
<BR>
<button id="mybtn" type="submit" name="submit_mail" value="Register">Register</button>
</form>
</div>
您不需要在表单元素上使用
id
,它们必然是表单的子元素。 (例如:myForm.gender.value
)。FormData
对象一起使用。
示例代码:
const myForm = document.querySelector('#my_form');
myForm.addEventListener('submit', e =>
{
e.preventDefault(); // disable form submission (and page reload)
// get data for your Ajax :
let formInputs = Object.fromEntries( new FormData(myForm) );
console.clear();
console.log(formInputs);
})
fieldset { width: fit-content; }
<div class="card">
<h2>Register</h2>
<form id="my_form" >
<input name="n" type="text" placeholder="Full Name" required>
<input name="e" type="email" placeholder="Email" required>
<fieldset>
<legend>Gender</legend>
<label>
<input name="gender" value="Male" type="radio" required>
<span>Male</span>
</label>
<label>
<input name="gender" value="Female" type="radio" >
<span>Female</span>
</label>
<label>
<input name="gender" value="Other" type="radio" >
<span>Other</span>
</label>
</fieldset>
<p><span id="status"></span></p>
<br>
<button type="submit" >Register</button>
<button type="reset" >clear</button>
</form>
</div>