在 Controller 文件中:
这就是我将验证错误 json_encode 到 View 的方式:
if ($this->form_validation->run() == FALSE) { //if validation does not run
$errors = $this->form_validation->error_array();
echo json_encode(['error' => true, 'errors' => $errors]);
}
在查看文件中:
if (res.errors) {
var errorMsgs = "";
errorMsgs += res.errors.name1 ? res.errors.name1 + "<br/>" : ""; //only if have an error msg.
errorMsgs += res.errors.name2 ? res.errors.name2 + "<br/>" : ""; //only if have an error msg.
errorMsgs += res.errors.name3 ? res.errors.name3 : ""; //only if have an error msg.
// SweetAlert
swal({
text: errorMsgs // error msg
});
}
SweetAlert 上的输出:
这是 Name1 字段错误消息。 <br/>
这是 Name2 字段错误消息。 <br/>
这是 Name3 字段错误消息。
最佳答案
自己找到了解决办法。 :D
只需使用“\n”代替“<br>
”!
errorMsgs += res.errors.name1 ? res.errors.name1 + "\n" : "";
关于javascript - 如何使用换行符在 SweetAlert 上输出 CodeIgniter 验证错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50072566/