我是Ajax的新手,所以我想知道如何在阵列中存储单选按钮的值,就像我为#34;问题","回答&# #34;和" testcases"。我需要通过PHP脚本发送信息,这就是我想存储数据的原因。任何帮助将不胜感激,谢谢。
<div id="container">
<form>
<div>
<input type='text' id='Question' class="form-control" placeholder="Question" />
<input type='text' id='Answer' class="form-control" placeholder="Answer" />
<input type='text' id='Testcases' class="form-control" placeholder="Testcases" />
<p style="margin-left:150px;">
<label>Difficulty level:</label>
<input type="radio" name="A" id='E' value="Easy" checked="checked" />
<label for='E'>Easy</label>
<input type="radio" name="A" id='M' value="Medium" />
<label for='M'>Medium</label>
<input type="radio" name="A" id='H' value="Hard" />
<label for='H'>Hard</label>
</p>
</div>
<input type='button' class='lg-button' onclick='send()' value='Submit' />
</form>
</div>
<script>
function send() {
var question = document.getElementById('Question').value;
var answers = document.getElementById('Answer').value;
var cases = document.getElementById('Testcases').value;
var ch = document.getElementsByName('A').value;
var data = {
'Question': question,
'Answer': answers,
'Testcases': cases,
'A': ch
};
var hr = new XMLHttpRequest();
hr.onreadystatechange = function() {
if (hr.readyState === 4) {
document.getElementById('send').innerHTML = hr.responseText;
}
};
hr.open("POST", "URL", true);
hr.send(JSON.stringify(data));
//alert(JSON.stringify(data));
}
</script>
答案 0 :(得分:0)
以下是工作代码,
function send() {
const question = document.getElementById('Question').value;
const answers = document.getElementById('Answer').value;
const testCases = document.getElementById('Testcases').value;
const level = document.querySelector('[name="A"]:checked').value;
const data = {
'Question': question || '',
'Answer': answers || '',
'Testcases': testCases || '',
'A': level
};
console.log(data);
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
document.getElementById('response').innerHTML = xhr.responseText;
}
};
xhr.open("POST", "URL", true);
xhr.send(JSON.stringify(data));
}
<div id="container">
<input type='text' id='Question' class="form-control" placeholder="Question" />
<input type='text' id='Answer' class="form-control" placeholder="Answer" />
<input type='text' id='Testcases' class="form-control" placeholder="Testcases" />
<p style="margin-left:150px;">
<label>Difficulty level:</label>
<input type="radio" name="A" id='E' value="Easy" checked="checked" />
<label for='E'>Easy</label>
<input type="radio" name="A" id='M' value="Medium" />
<label for='M'>Medium</label>
<input type="radio" name="A" id='H' value="Hard" />
<label for='H'>Hard</label>
</p>
<input type='button' class='lg-button' onclick='send()' value='Submit' />
<p id="response"></p>
</div>