我有一个使用codeigniter内置帮助器进行服务器端验证的表单。我正在使用ajax在我的控制器中发送数据。它返回一个json响应,我在成功函数中使用它。
这是控制器:
@Directive({ selector: '[addressPrediction]' })
export class AddressPredictionDirective {
@Output() onpredict: EventEmitter<any[]> = new EventEmitter<any[]>();
@Output() onsearching: EventEmitter<boolean> = new EventEmitter<boolean>();
resolveSuggestions: (predictions, status) => void;
autocompleteService: any;
search: any;
input: string = '';
country: string = 'cl';
constructor(private el: ElementRef){}
ngOnInit(): void {
this.autocompleteService = new google.maps.places.AutocompleteService();
this.resolveSuggestions = (predictions, status) => {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert('AutocompleteService error: '.concat(status));
return;
}
let places: Prediction[] = [];
for(let i: number = 0; i<predictions.length; i++){
let place: Prediction = { id: predictions[i].reference, name: predictions[i].description };
places.push(place);
}
this.onpredict.emit(places);
};
}
@HostListener('keyup') onKeyUp() {
if(this.el.nativeElement.value.trim() != this.input.trim()){
this.input = this.el.nativeElement.value;
if(this.input.length > 4){
this.searchAddress();
}
}
}
@HostListener('keydown') onKeyDown() {
if(this.search){
clearInterval(this.search);
this.search = null;
}
}
private searchAddress(): void {
this.onsearching.emit(true);
this.search = setTimeout(() => {
this.autocompleteService.getPlacePredictions({
input: this.input,
componentRestrictions: { country : this.country }
}, this.resolveSuggestions);
clearInterval(this.search);
}, 3000);
}
}
这是ajax代码:
$this->form_validation->set_rules($this->validates()['create']);
if($this->form_validation->run()){
$response['status'] = true;
$response['message'] = "Successfully added user";
$response['page'] = base_url('/user');
$this->user_model->user_add($this->form_input()['create']);
}else{
$errors = array();
foreach ($this->input->post() as $key => $value) {
$errors[$key] = form_error($key);
}
$response['errors'] = array_filter($errors);
$response['status'] = false;
}
$this->jsonresponse($response);
以下是观点:
$.ajax({
url:site_url('user/user_add'),
data: $('#user_form').serialize(),
type: 'post',
dataType: 'json',
beforeSend: function(){
console.log('test');
},
success: function(response){
if(response.status == true){
alert(response.message);
}else{
$.each(response.errors,function(key,val){
var names = ["firstname","middlename","lastname","username","job"];
if(names.indexOf(key) > -1){
$('input[name="' + key + '"]').next().html(val);
}else{
$('input[name="' + key + '"]').next().html('');
}
});
}
}
});
我检查控制器的响应状态是成功还是失败。如果失败,它将迭代响应错误然后显示它。
我的问题是如果一个字段已经有效,它将不会隐藏或删除。我使用带有字段名称的数组来检查它是否包含与响应错误相同但它不起作用。
表单验证正在运行,jsonresponse是我的MY_Controller中的一个函数,它返回一个json编码数据。
答案 0 :(得分:0)
请参阅此文档以了解验证的设置规则 https://www.codeigniter.com/userguide3/libraries/form_validation.html
//$this->form_validation->set_rules($this->validates()['create']);
如果您正确设置规则,请在代码中更改以下内容
if($this->form_validation->run()){
$response['status'] = true;
$response['message'] = "Successfully added user";
$response['page'] = base_url('/user');
$this->user_model->user_add($this->form_input()['create']);
}else{
$response['errors'] = $this->form_validation->error_array();//generate error array with input post key
$response['status'] = false;
}
//set page header in JSON format
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
更改Ajax的成功回调
success: function(response){
//remove all errors
$('#patient_form .form-group').find('span.text-danger').text('');
if(response.status == true){
alert(response.message);
}else{
var names = ["firstname","middlename","lastname","username","job"];
//appent all errors 1-1
$.each(response.errors,function(key,val){
if(names.indexOf(key) > -1){
$('#patient_form input[name="'+key+'"]').parent('.form-group').children('span.text-danger').text(val);
}
});
}
},