我在给定的数组下面给出了我的Ajax响应,现在我想将这些数组值附加到我的html div中,为此我已经使用了循环,但是出了什么问题呢?我正在获得下面的输出(请参阅附件图像)
//Array from php page
Array (
[FirstName] => Please enter your first name
[LastName] => Please enter last name
[Email] => This e-mail address is already associated to another account.
[ConfirmPassword] => Passwords do not match
)
//jquery
success:function(result){
for (var i = 0; i < result.length; i++)
{
console.log(result[i]);
$("#error_div").append(result[i]);
}
}
//want this output to append in div
Please enter your first name
Please enter last name
This e-mail address is already associated to another account.
Passwords do not match
JavaScript中没有关联数组,它只是具有属性的对象。
如果要迭代此对象,可以使用for...in
循环:
for (var key in result)
{
console.log(result[key]);
$("#error_div").append(result[key]);
}
您还可以将for...of
循环与Object.values()
一起使用以直接获取值:
for (let value of Object.values(result))
{
console.log(value);
$("#error_div").append(value);
}
Javascript没有关联数组。您可以遍历对象,但是由于无论如何都使用jQuery,因此可以使用each()
。如果性能很重要,请使用for循环。
var values = {
'FirstName': 'Please enter your first name ',
'LastName': 'Please enter last name ',
'Email': 'This e-mail address is already associated to another account. ',
'ConfirmPassword' : 'Passwords do not match '
};
var errors = $('#error_div');
$.each(values, function( index, value ) {
errors.append(value);
errors.append('<br>');
});