I currently have a ajax call sending data to a controller and retrieving json data back.
我目前有一个ajax调用,将数据发送给控制器并返回json数据。
the values that come back look like this
返回的值是这样的。
{
"old": "The Old Password field is required.",
"new": "The New Password field is required.",
"new_confirm": "The Confirm New Password field is required."
}
now if the any of the json string is empty i want to hide the warning.
现在,如果任何json字符串为空,我想要隐藏警告。
so far i have the below but i want to know if there is a better way to loop through the data with creating mutiple if/else statments
到目前为止,我已经有了下面的内容,但是我想知道是否有更好的方法通过创建多个if/else语句来循环数据
$(document).ready(function() {
$('#changepassword').click(function () { // form submit button
$.ajax({
url: "auth/change_password", // php controller
async: false,
type: "POST",
data: $("#change_password_form").serialize(), //pass all form data
dataType:"json",
success: function(data) {
if (data.old == "") {
$("#old").hide(); // hide old password alert div
}
else {
$("#old").show(); // show warning div
$("#old").empty(); // empty previous warning contents
$("#old").append(data.old); // append json string
};
//$('#ajax-content-container').html(data);
}
})
});
})
2 个解决方案
#1
3
So you basically want to do the same for all 3 properties? Just use a for...in loop then.
所以你基本上想对所有的3个属性都做同样的事情?只使用一个……在循环。
for(var prop in data){
if(data[prop] == ""){
$("#" + prop).hide();
}else{
$("#" + prop).show();
$("#" + prop).empty();
$("#" + prop).append(data[prop]);
};
#2
0
If all properties match the respective DOM elements' ids you can use a for..in
loop:
如果所有属性都匹配各自的DOM元素的id,可以使用a for.。在循环:
for(var prop in data)
{
var element = $('#' + prop);
if(obj[prop]){
// There is error message -> Show it
element.text(data[prop]).show();
} else {
// There isn't error message -> Hide it
element.hide();
}
}
#1
3
So you basically want to do the same for all 3 properties? Just use a for...in loop then.
所以你基本上想对所有的3个属性都做同样的事情?只使用一个……在循环。
for(var prop in data){
if(data[prop] == ""){
$("#" + prop).hide();
}else{
$("#" + prop).show();
$("#" + prop).empty();
$("#" + prop).append(data[prop]);
};
#2
0
If all properties match the respective DOM elements' ids you can use a for..in
loop:
如果所有属性都匹配各自的DOM元素的id,可以使用a for.。在循环:
for(var prop in data)
{
var element = $('#' + prop);
if(obj[prop]){
// There is error message -> Show it
element.text(data[prop]).show();
} else {
// There isn't error message -> Hide it
element.hide();
}
}