2014-11-10 6 views
0

я проверить мой формуляр с AJAX и получить обратно следующий JSon объект:JQuery, как пройти через JSON объект динамически

{"username":["Please enter a username"],"email":["Please enter an email"], 
"plainPassword":{"first": ["Please enter a password"]},"firstname": 
["This value should not be blank."],"lastname":["This value should not be blank."], 
"terms":["This value should be true."],"privacy":["This value should be true."], 
"captcha":["Code does not match"],"securityQuestion":["This value should not be blank."], 
"plainSecurityAnswer":["This value should not be blank."],"intention": 
["This value should not be blank."],"addresses":[{"state":["This value should not be blank."], 
"city":["This value should not be blank."],"zipcode":["This value should not be blank."], 
"country":["This value should not be blank."]}]} 

Ключи отображаются в полях ввода идентификатор всегда по: вар ид = «fos_user_registration_form_» + ключ;

Я хочу представить эти ошибки эффективным образом в виде подсказок к полям. Для этого я написал следующий код JQuery (где обратный вызов возвращаемого JSON объект):

$.each(callback, function(key, entry) { 
    if(key != "addresses" && key != "plainPassword") 
     { 
     var id = "#fos_user_registration_form_" + key; 
     $(id).tooltip('destroy'); 
     $(id).tooltip({'title': entry}); 
     $(id).closest('div[class="form-group"]').addClass('has-error'); 
     }else if(key == "addresses"){ 
     $.each(entry[0], function(keyAddress, entryAddress) { 
      var id = "#fos_user_registration_form_" + key + "_0_" + keyAddress; 
      $(id).tooltip('destroy'); 
      $(id).tooltip({'title': entryAddress}); 
      $(id).closest('div[class="form-group"]').addClass('has-error'); 
     }); 
     }else if(key == "plainPassword") 
     { 
      var id= "#fos_user_registration_form_plainPassword_first,#fos_user_registration_form_plainPassword_second"; 
      $(id).tooltip('destroy'); 
      $(id).tooltip({'title': entry.first}); 
      $(id).closest('div[class="form-group"]').addClass('has-error'); 
}}); 

Это работает, но я думаю, что не очень динамичен, потому что я знаю, в этом случае, что элементы ключа «Адреса» и «plainPassword» не являются строками и что я должен повторять их снова (здесь только по адресам).

Есть ли более хороший способ сделать это, используя только ключ и переменную ввода петель, не зная «ключевых» имен json?

Я подумал о чем-то вроде: В то время как entry! == "string", повторите так же длинные записи, как есть другой массив или объект в нем и создайте переменную id. Когда в качестве «записи» есть поле строки, используйте его в виде текста всплывающей подсказки.

Надеюсь, вы, ребята, можете мне помочь.

С уважением.

ответ

0

Рекурсия сделает это!

например http://repl.it/3hK/5

код -

var id_stub = "#fos_user_registration_form_" 

// Here's the recursive function - we kick it off below. 
function process(thing, id) { 
    var key 
    for (key in thing) { 
     // Handle the arrays 
     if ('length' in thing[key]) { 

      // Handle the end - we found a string 
      if (typeof thing[key][0] == "string") { 
       var html_id = id_stub + id + key 
       var err_msg = thing[key][0] 

       console.log(html_id, ":", err_msg) 

       // Now do your jquery using the html_id and the err_msg... 
      } 
      // Else we found something else, so recurse. 
      else { 
       var i = 0; 
       while (i < thing[key].length) { 
        process(thing[key][i], key + "_" + i + "_") 
        i++ 
       } 
      } 
     } 

     // Handle the objects by recursing. 
     else { 
      process(thing[key], key + "_") 
     } 
    } 
} 

// Start the recursion from here. 
process(callback, "") 

Я добавил дополнительный адрес, чтобы проверить, как этот код обрабатывает вложенные адреса, и с помощью этого я получаю это в консоли:

#fos_user_registration_form_username : Please enter a username 
#fos_user_registration_form_email : Please enter an email 
#fos_user_registration_form_plainPassword_first : Please enter a password 
#fos_user_registration_form_firstname : This value should not be blank. 
#fos_user_registration_form_lastname : This value should not be blank. 
#fos_user_registration_form_terms : This value should be true. 
#fos_user_registration_form_privacy : This value should be true. 
#fos_user_registration_form_captcha : Code does not match 
#fos_user_registration_form_securityQuestion : This value should not be blank. 
#fos_user_registration_form_plainSecurityAnswer : This value should not be blank. 
#fos_user_registration_form_intention : This value should not be blank. 
#fos_user_registration_form_addresses_0_state : This value should not be blank. 
#fos_user_registration_form_addresses_0_city : This value should not be blank. 
#fos_user_registration_form_addresses_0_zipcode : This value should not be blank. 
#fos_user_registration_form_addresses_0_country : This value should not be blank. 
#fos_user_registration_form_addresses_1_state : This value should not be blank. 
#fos_user_registration_form_addresses_1_city : This value should not be blank. 
#fos_user_registration_form_addresses_1_zipcode : This value should not be blank. 
#fos_user_registration_form_addresses_1_country : This value should not be blank. 

и устанавливает переменные, необходимые для работы jQuery.

+0

Удивительно! Спасибо большое sifriday! Я также пытался использовать рекурсию, но не смог получить удовлетворительный результат. У меня есть еще один вопрос к вашему решению: моя IDE (phpstorm) сообщает мне, что доступ к ключу с помощью «[key]» не так хорош: «Возможная итерация по сравнению с непредвиденными членами, возможно, отсутствующая проверка hasOwnProperty». Не хватает ли чека? –

+0

вещь hasOwnProperty полезна, чтобы убедиться, что вы не итерируете свойства, которые вы унаследовали от прототипа. См. Http://stackoverflow.com/questions/3010840/loop-through-array-in-javascript ... поскольку ваш оригинальный объект находится под вашим контролем и исходит от JSON, вы можете быть уверены, что вам не нужна эта проверка , Надеюсь, это поможет! – sifriday

+0

yep. принял ваш ответ :) –

0
function isValidationMessage(entry) { 
     return entry.length === 1 && typeof entry[0] === 'string'; 
    } 

function displayValidationMessage(key, message){ 
    var id = "#fos_user_registration_form_" + key; 
      $(id).tooltip('destroy'); 
      $(id).tooltip({'title': message}); 
      $(id).closest('div[class="form-group"]').addClass('has-error'); 
} 

function displayValidationMessageForArray(key, entries) { 
    for(var i = 0; i < entries.length; i++) { 
    $.each(entries[i], function(keyAddress, entryAddress) { 
     displayValidationMessage(key + "_i_" + keyAddress, entryAddress); 
    }) 
    } 

} 

function displayValidationMessageForObject(key, entries) { 
    $.each(entries, function(entry, message) { 
    displayValidationMessage(key + "_" +entry, message); 
    }) 
} 

function displayAllValidationMessages(callback) { 

    $.each(callback, function(key, entry) { 
     if(isValidationMessage(entry)) { 
      displayValidationMessage(key, entry); 
     }else if($.isArray(entry)){ 
      displayValidationMessageForArray(key, entry); 
     }else { 
      displayValidationMessageForObject(key, entry); 
     } 
    }); 
} 

не полностью протестировано, идея заключается в том, чтобы извлечь if else малой функции, и использовать их как можно больше

+0

благодарю вас за помощь, sifriday уже отправил красивый путь ниже :) –

Смежные вопросы