我有一個用戶表單,它使得AJAX調用返回一個JSON對象,以供我操縱依賴於用戶輸入或不輸入的內容。 當出現錯誤時(例如用戶沒有在輸入字段中放入任何東西),輸入框名稱將與錯誤消息一起返回並存儲在一個錯誤數組中,然後返回到JSON對象中。這是因爲我會接着輸入框名稱,使用jQuery在DOM中找到它們,並在出現錯誤的輸入框之後放置帶有錯誤消息的跨度。 我遇到的問題是,當我通過JSON對象中的返回錯誤循環時,它不允許我訪問錯誤(輸入名稱)的鍵,只有數組位置(0,1,2,3,4,等等)。 我可以在JSON/jQuery對象中訪問關聯數組鍵嗎?還是我在某處出錯?如何在AJAX請求中訪問JSON對象的子陣列鍵
這裏是我的代碼(我只包括其相關的代碼):
這是AJAX調用返回
success : function(data) {
if(data.errors == 'undefined' && data.errors == null) {
...
} else {
jQuery(data.errors).each(function(k, v) {
var html = "<span class='inputError'>" + v + "</span>";
var errorSpan = '.signUpInputWrap input[name=' + k + ']';
...
});
}
}
所以,在那裏你可以看到我我試圖使用'k'(這是json中返回的輸入框名稱),所以我可以在DOM中訪問它。而不是使用返回的名稱,儘管它使用數組位置。
這裏是產生錯誤數組,並返回它的PHP:
$result = $this->validateInput($post);
..
if($result['result'] == true) {
...
} else {
echo json_encode(array('errors' => $result['errors']));
}
private function validateInput($input) {
$errors = array();
foreach($input as $key => $inputItem) {
if($key == 'sports_instructed' || $key == 'activities_qualified' | $key == 'sports_qualified') {
continue;
}
if(empty($inputItem)) {
if($key == 'dob' || $key == 'dobMonth' | $key == 'dobYear') {
$errors['dob'] = "Please ensure all values are entered for date of birth";
unset($input[$key]);
}
$pieces = explode('_', $key);
foreach($pieces as &$piece) {
$piece = ucfirst($piece);
}
$name = implode(" ", $pieces);
$errors[$key] = "Please enter a value for " . $name;
}
}
if(empty($errors)) {
$result = array('result' => true);
} else {
$result = array('result' => false, 'errors' => $errors);
}
return $result;
}
這裏是JSON結果(因爲你可以看到,最關鍵的是我想用搶元素的輸入名稱
{"errors":{"first_name":"Please enter a value for First Name","last_name":"Please enter a value for Last Name","telNum":"Please enter a value for TelNum","dob":"Please ensure all values are entered for date of birth","dobMonth":"Please enter a value for DobMonth","address":"Please enter a value for Address","city":"Please enter a value for City","county":"Please enter a value for County","postcode":"Please enter a value for Postcode","password":"Please enter a value for Password","password_confirm":"Please enter a value for Password Confirm"}}
是否有可能對我來說,的javascrip/jQuery的訪問副教授陣列就像我可以在PHP:使用jQuery)內環路? 謝謝
你能告訴我們'$ POST'的內容? – Mina
JSON結果是什麼樣的? – devnull69
添加了JSON結果 – devoncrazylegs