gpt4 book ai didi

javascript - 检查 json 对象内容和应用 jquery 的更有效方法

转载 作者:行者123 更新时间:2023-11-30 12:13:17 26 4
gpt4 key购买 nike

我目前有一个 ajax 调用将数据发送到 Controller 并检索 json 数据。

返回的值是这样的

{
"old": "The Old Password field is required.",
"new": "The New Password field is required.",
"new_confirm": "The Confirm New Password field is required."
}

现在,如果任何 json 字符串为空,我想隐藏警告。

到目前为止我有以下内容,但我想知道是否有更好的方法通过创建多个 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);
}
})
});
})

最佳答案

所以您基本上想对所有 3 个属性执行相同的操作?只需使用 for...in 循环即可。

for(var prop in data){
if(data[prop] == ""){
$("#" + prop).hide();
}else{
$("#" + prop).show();
$("#" + prop).empty();
$("#" + prop).append(data[prop]);
};

关于javascript - 检查 json 对象内容和应用 jquery 的更有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33165714/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com