如何在jquery中使用'for'迭代这样的数组。这个让我完全迷失了。我不知道如何从这样的数组中获取这些值,我无法改变数组的完成方式。
//Php
$errors['success'] = false;
$errors['#errOne'] = "Enter a valid username";
$errors['#errTwo'] = "Enter a valid email";
$errors['#errThree'] = "Enter a valid password";
echo json_encode($errors);//
dataType:"json",
cache:false,
success: function(data){
for (i=1; i<?; i++){//Start at 1
//I'm totally lost here.
//Output: "#errOne" "Enter a valid username" ->Loop thru remaining messages
}
},
答案 0 :(得分:1)
由于您将数据作为参数传递,您可以访问数据
尝试这样的事情:
var $errors = {};
$errors['success'] = false;
$errors['#errOne'] = "Enter a valid username";
$errors['#errTwo'] = "Enter a valid email";
$errors['#errThree'] = "Enter a valid password";
data : $errors;
success: function(data){
for (var i in data ){
console.log(i + ':' + data[i]);
}
答案 1 :(得分:1)
可能你需要这个:
success: function(data){
$.each(data, function(key, value) {
alert(key + ': ' + value);
});
}
答案 2 :(得分:0)
for (var key in data){
alert(key); // gives keys success, #errOne, #errTwo, #errThree
alert(data[key]); // gives values false, Enter a valid username, Enter a valid email, Enter a valid password
}
答案 3 :(得分:0)
如果你的PHP代码是这样的:
// Use $errors = array(...) if your PHP version is < 5.4
$errors = [
'success' => false, // Why is 'success' part of the $errors array?
'error_1' => 'Enter a valid username.',
'error_2' => 'Enter a valid email.',
'error_3' => 'Enter a valid password.'
];
print json_encode($errors);
,然后在您的JavaScript中,您可以执行以下操作:
$.ajax({
'url': 'your.url.com/data.json',
'dataType': 'json',
'cache': false, // Why are you doing this?
'success': function (json_data) {
var i = json_data.length;
while (i--) {
alert(json_data[i]); // Or whatever you want to do with the data.
}
}
});
我很确定这是最好的方法之一。如果我错了,请有人纠正我。