我使用 ajax 创建了一个表单,它将数据作为 json 数组发布到一个单独的 php 文件中。将表单发布到 php 处理程序的标记 ajax 是:
$.ajax({
dataType: "json",
type: "post",
url: "ajax.php?action=add_driver",
data: $("form#addDriver").serialize(), // serializes the form's elements.
beforeSend: function()
{
$('.error, .success, .notice').remove();
},
success: function(json)
{
if (json['status']=='success'){
alert(json['message']);
}else{
if(json['error']['driver_firstname']){
$("input[name=driver_firstname]").after('<div class="error">'+json['error'['driver_firstname']+'</div>');
}
if(json['error']['driver_surname']){
$("input[name=driver_surname]").after('<div class="error">'+json['error']['driver_surname']+'</div>');
}
if(json['error']['driver_dob']){
$("input[name=driver_dob]").after('<div class="error">'+json['error']['driver_dob']+'</div>');
}
if(json['error']['driver_address']){
$("input[name=driver_address]").after('<div class="error">'+json['error']['driver_address']+'</div>');
}
if(json['error']['driver_postcode']){
$("input[name=driver_postcode]").after('<div class="error">'+json['error']['driver_postcode']+'</div>');
}
if(json['error']['driver_city']){
$("input[name=driver_city]").after('<div class="error">'+json['error']['driver_city']+'</div>');
}
if(json['error']['driver_county']){
$("input[name=driver_county]").after('<div class="error">'+json['error']['driver_county']+'</div>');
}
if(json['error']['driver_email']){
$("input[name=driver_email]").after('<div class="error">'+json['error']['driver_email']+'</div>');
}
if(json['error']['driver_tel']){
$("input[name=driver_tel]").after('<div class="error">'+json['error']['driver_tel']+'</div>');
}
if(json['error']['driver_mobile']){
$("input[name=driver_mobile]").after('<div class="error">'+json['error']['driver_mobile']+'</div>');
}
//These are the series of validation checks carried out before submission//
}
});
这被传递到 url 中命名的文件 ajax.php,该文件使用 php 验证检查错误,如果一切正常,则应该插入到数据库中。这部分的编码标记是:
<?php
$json = array();
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//for the first field only//
$driver_firstname = tep_db_prepare_input($HTTP_POST_VARS['driver_firstname']);
if (strlen($driver_firstname)<4){
$json['error']['driver_firstname'] = 'First Name is required!';
}
if (isset($json['error']) and !empty($json['error'])){
$json['status'] = 'error';
$json['message'] = 'Please check your error(s)!';
}else{
$sql_data_array = array('driver_firstname' => $driver_firstname);
tep_db_perform(TABLE_DRIVERS, $sql_data_array);
$driver_id = tep_db_insert_id();
$json['status'] = 'success';
$json['message'] = 'Data has been successfully updated!';
}
}
echo json_encode($json);
?>
出于某种原因,它没有从浏览器将任何值发布到 php 文件,并且显示一个空白数组。当我使用“get”类型时,它可以工作。谁能帮忙告诉我为什么它不适用于“帖子”类型?如果需要 ajax.php 部分,请告诉我...