从ajax函数获取json响应,该函数返回以下代码:
["Please enter a Name","Please enter a Email","Please enter a Date","Please enter a message"]
问题是我当前的代码只显示最后一条消息,而不是所有消息。
Jquery代码是:
var result = jQuery.parseJSON(response);
console.log(response);
$.each(result, function(key, value){
if(key == 'success') {
// console.log(response);
success.find(".message").text(value);
success.slideDown();
success.delay(4000).fadeOut();
}
else {
// console.log(response);
error.find(".message").text(value);
error.slideDown();
}
})
如何单独显示每条错误消息?
答案 0 :(得分:1)
您的代码正在替换文字。而是尝试使用追加
success.find(".message").append(value + '<br />');
与错误error.find(".message").append(value + '<br />');
答案 1 :(得分:0)
我会考虑改变你如何构建反应。
在此处查看代码的js小提示:http://jsfiddle.net/xrmgeazs/或http://jsfiddle.net/xrmgeazs/1/并带有成功选项
例如来自php:
$response = json_encode( array(
'success' => false,
'errors' => array(
'name =>"Please enter a Name",
'email => "Please enter a Email"
)
) );
echo $ response;
你的js例如:
var result = jQuery.parseJSON(response);
if( result.success ){
//do your success code here
} else {
//start by clearing previous errors
$('form p.error').hide();
//loop your errors here
for (var key in result.errors){
var errorName = key;
var errorMessage = result.errors[key];
//now place your error and show accordingly.
$( 'div.'+key ).append('<p>'+errorMessage+'</p>');
}
}
HTML EG:
<form action="something.php" method="post">
<!-- add rel fields as appropriate -->
<!-- also note this is a very simple structure and could be expanded for richer ui -->
<div class="name">
<input type="text" name="name"/>
</div
<div class="email">
<input type="text" name="name"/>
</div
</form>