我被一个多维形式的问题所困扰。
我想要做的是通过ajax发送一个JSON,其结构如下:
{
"user": 1,
"quiz": 25,
"questions": {
// question 132, hidden input (checkboxes)
"132": [24536, 566, 64],
// question 133, hidden input (mixed checkboxes/textarea)
"133": [2345, "some text from a text area", 456],
// question 134, hidden input (radio buttons)
"134": [876]
},
"other_data": [2, 543, "test", 989]
}我的表单:
<form id="myForm" action="myAPI.php">
<input type="hidden" name="user" value="1">
<input type="hidden" name="quiz" value="25">
<p>Question A</p>
<input type="hidden" name="question" value="132">
a1
<input name="answer[]" type="checkbox" value="a"><br>
a2
<input name="answer[]" type="checkbox" value="b"><br>
a3
<input name="answer[]" type="checkbox" value="c"><br>
<p>Question B</p>
<input type="hidden" name="question" value="133" >
a1
<input name="answer[]" type="checkbox" value="d"><br>
a2
<input name="answer[]" type="checkbox" value="e"><br>
a3
<textarea name="answer_" rows="3"></textarea><br>
<p>Question C</p>
<input type="hidden" name="question" value="134">
a1
<input name="answer" type="radio" value="f"><br>
a2
<input name="answer" type="radio" value="g"><br>
a3
<input name="answer" type="radio" value="h"><br>
<hr>
<button type="submit">invia</button>
</form>我的Ajax
var myForm = $('form#myForm'),
response = $('#myForm-response');
myForm.submit(function(e)
{
e.preventDefault();
var url = myForm.attr('action'),
data = JSON.stringify(myForm.serializeArray());
// JSON example I'd like to send
/*var data = {
"user": 1,
"quiz": 25,
"questions": {
"132": ['24536, 566, 64'],
"133": [2345, "some text from a text area", 456],
"134": [876]
}
}*/
$('#console-output').html('data : ' + data);
console.log('data : ' + data);
$.ajax(
{
method : "POST",
url : url,
data : data,
processData: false,
dataType : 'html',
beforeSend : function()
{
//console.log('beforeSending: ' + data);
},
success : function(result)
{
//console.log('success!' + result);
response.html(result);
},
error : function(xhr, ajaxOptions, thrownError)
{
//console.log(xhr);
if(typeof console != "undefined")
console.log(xhr + " - " + ajaxOptions + " - " + thrownError);
response.html(xhr + " - " + ajaxOptions + " - " + thrownError);
},
complete : function()
{
//console.log('complete:');
}
});
})输出结果为:
[{
"name": "user",
"value": "1"
}, {
"name": "quiz",
"value": "25"
}, {
"name": "question",
"value": "132"
}, {
"name": "answer[]",
"value": "b"
}, {
"name": "answer[]",
"value": "c"
}, {
"name": "question",
"value": "133"
}, {
"name": "answer[]",
"value": "e"
}, {
"name": "answer_",
"value": "test"
}, {
"name": "question",
"value": "134"
}, {
"name": "answer",
"value": "g"
}]有什么建议吗?我做错了什么?
发布于 2016-01-15 18:53:54
我用formToObject.js解决了:)
https://stackoverflow.com/questions/34795933
复制相似问题