我想将数据从html页面发送到服务器 下面是我的json示例。 在我的html页面问题标签和这四个选项,如A,B,C,D和选项是单击发送按钮后单选按钮形式我想发送如下json格式的数据到远程服务器。
{
"questions": [
{
"question": "What is the answer. 2+3=?",
"answer": "B"
},
{
"question": "What is the answer. 3-1=?",
"answer": "A"
},
{
"question": "What is the answer. 3*2=?",
"answer": "B"
},
{
"question": "What is the answer. 3/3=?",
"answer": "A"
},
{
"question": "What is the answer. 6%3=?",
"answer": "D"
},
{
"question": "What is the answer. 6+3=?",
"answer": "NA"
},
{
"question": "What is the answer. 2+3+3=?",
"answer": "A"
},
{
"question": "What is the answer. 3+3-2=?",
"answer": "NA"
},
{
"question": "What is the answer. 2*3*3=?",
"answer": "D"
},
{
"question": "What is the answer. 2*3+3=?",
"answer": "B"
}
]
}
答案 0 :(得分:1)
您可以使用ajax将数据发送到远程服务器(让您的json保存在JS中的变量 - var json_data
中):
$.ajax({
type : "POST",
contentType : "application/json",
url : "url_for_remote_server",
data : json_data,
dataType : 'json',
success : function(data) {
console.log("SUCCESS: ", data);
},
error : function(e) {
console.log("ERROR: ", e);
},
done : function(e) {
console.log("DONE");
}
});
<强>更新强>
请参阅下面的代码bock,其中显示了如何从HTML获取数据并通过它形成json数组:
$(function() {
$('.submitBtn').on('click', function(e) {
var jsonArr = [];
$('.ques_block').each(function(i) {
var text = $(this).find('label').text();
var option = $(this).find("select").val();
jsonArr.push({
'text': text,
'option': option
});
});
console.log(jsonArr);
});
});
.options {
margin-left: 20px;
margin-top: 10px;
}
.ques_block{
margin-top: 30px;
}
.submitBtn {
margin-top: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test-block">
<div class="ques_block">
<label>Q1. Select any 1 option from below?</label>
<div class='options'>
<select>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
</div>
</div>
<div class="ques_block">
<label>Q1. Select any 1 option from below?</label>
<div class='options'>
<select>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
</div>
</div>
<button class="submitBtn">
Submit
</button>
</div>
希望这有帮助!