这是我的ajax代码。我不知道为什么它继续给我空值的问题在哪里。
$('#btnSubmit').click(function(event) {
var formData = {
'name' : $('input[name=name1]').val(),
'branch_address' : $('input[name=bAddress1]').val(),
'officer_in_charge' : $('input[name=officer1]').val(),
'contact_number' : $('input[name=contactN1]').val()
};
$.ajax({
type : 'POST',
dataType : 'json',
url : "process_save.php",
data : formData,
encode : true
})
}
输入值来自这里
<form id="form1">
<div class="modal-body">
<input type="text" class="form-control" name="name1" />
<input type="text" class="form-control" name="bAddress1" />
<input type="text" class="form-control" name="officer1" />
<input type="text" class="form-control" name="contactN1" />
</div>
<div class="modal-footer">
<input id="btnSubmit" type="submit" value="SUBMIT" class="btn" />
</div>
</form>
process_save.php包含此代码
if( !empty( $_POST ) ){
// convert form data to json format
$data = array(
"name" => $_POST['name1'],
"branch_address" => $_POST['bAddress1'],
"officer_in_charge" => $_POST['officer1'],
"contact_number" => $_POST['contactN1']
); //processes the fields on the form
$json = json_encode( $data );
$file = 'entries.json';
// write to file
file_put_contents( $file, $json, FILE_APPEND);
}
答案 0 :(得分:0)
您的问题是您的PHP代码使用的是表单输入的原始名称,而不是var formData
中的名称。因此,将您的php $_POST
密钥更改为var formData
密钥 -
javascript code-
// use these keys
var formData = {
'name' : $('input[name=name1]').val(),
'branch_address' : $('input[name=bAddress1]').val(),
'officer_in_charge' : $('input[name=officer1]').val(),
'contact_number' : $('input[name=contactN1]').val()
};
php code -
// as the $_POST keys
$data = array(
"name" => $_POST['name'],
"branch_address" => $_POST['branch_address'],
"officer_in_charge" => $_POST['officer_in_charge'],
"contact_number" => $_POST['contact_number']
);