我有一个从用户那里收集信息的表单。该表单由 10 个输入文本字段组成。输入文本字段的单个值通过var first_name = $("#fname").val()
作为示例访问并传递给var postdata = {'fname':first_name};
然后传递给 ajax,url: "<?php echo base_url(); ?>main_controller/save_data", data: postdata
然后控制器函数将再次收集它。如果我有 30 个输入文本字段然后以这种方式使用,那将花费我很多时间。以微型方式使用 javascript 传递大量输入字段值的最佳方法是什么?这有捷径吗?非常感谢。我在下面有一个示例代码。
意见:
<input class="input input-large" type="text" name="fname" id="fname" value=""/>
<input class="input input-large" type="text" name="lname" id="lname" value=""/>
<input class="input input-large" type="text" name="address" id="address" value=""/>
<input class="input input-large" type="text" name="age" id="age" value=""/>
<input class="input input-large" type="text" name="height" id="height" value=""/>
<input class="input input-large" type="text" name="gender" id="gender" value=""/>
<input class="input input-large" type="text" name="school" id="school" value=""/>
<input class="input input-large" type="text" name="course" id="course" value=""/>
<input class="input input-large" type="text" name="year" id="year" value=""/>
<input class="input input-large" type="text" name="date_of_birth" id="date_of_birth"
value=""/>
<button class="btn btn-success" id="save" name="save">Save</button>
<script type="text/javascript">
$("#save").click(function(){
var fname = $("#fname").val();
var lname = $("#lname").val();
var address = $("#address").val();
var age = $("#age").val();
var height = $("#height").val();
var gender = $("#gender").val();
var school = $("#school").val();
var course = $("#course").val();
var year = $("#year").val();
var date_of_birth = $("#date_of_birth").val();
var postdata = {
'fname': fname,
'lname': lname,
'address': address,
'age': age,
'height': height,
'gender': gender,
'school': school,
'course': course,
'year': year,
'date_of_birth': date_of_birth
};
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>main_controller/save_data",
data: postdata,
success: function (data) {
if (data.notify) {
alert('success');
} else {
alert('Failed');
}
}
});
});
</script>
控制器:
function save_data(){
$fname = $this->input->post('fname');
$lname = $this->input->post('lname');
$address = $this->input->post('address');
$age = $this->input->post('age');
$height = $this->input->post('height');
$gender = $this->input->post('gender');
$school = $this->input->post('school');
$course = $this->input->post('course');
$year = $this->input->post('year');
$date_of_birth = $this->input->post('date_of_birth');
$this->insert_model->save_data($fname,$lname,$address,$age,$height,$gender,$school,$course,$year,$date_of_birth);
}