检索JSON数据无法按预期工作

时间:2017-04-04 15:36:29

标签: javascript php jquery json ajax

下面我在主PHP文件中有一个JSON数组。正如您所看到的,$firstname_error$lastname_error是我打算传递给AJAX的变量,以便将它显示在两个单独的div中。目前没有任何东西出现,我不确定为什么。非常感谢任何见解。

PHP& JSON

if (empty($_POST["City"])) {
    $city_error = "A city required";
}

if (empty($_POST["E-mail"])) {
    $email_error = "E-mail is required";
}

echo json_encode(array("city" => $city_error, "email" => $email_error));

AJAX

$(document).ready(function () {
    $(".form").submit(function (e) {
        e.preventDefault();

        $.ajax({
            type: "POST",
            url: "destination.php",
            data: $(this).serialize(),
            dataType: 'json',
            cache: false,
            success: function (data) {
                if (data.trim() != '') {
                    $('.error4').html(data.city);
                    $('.error5').html(data.email);
                }
            },
            error: function () {

            }
        });
    });
});

.error4.error5目前没有显示任何内容。

3 个答案:

答案 0 :(得分:2)

我认为您的if条件不正确,因此请尝试更改success函数:

success: function (data) {
    if (data.city.trim() != '') {
        $('.error4').html(data.city);
    } 
    if (data.email.trim() != '') {
        $('.error5').html(data.email);
    }
}

答案 1 :(得分:2)

由于您dataType: 'json',传递给success函数的数据变量将成为一个对象,因此您无法使用trim()

要检查回复中是否存在值,您可以data使用hasOwnProperty

success: function (data) {

    $('.error4').text(data.hasOwnProperty('city') ? data.city : '');
    $('.error5').text(data.hasOwnProperty('email') ? data.email : '');
},

希望这有帮助!

答案 2 :(得分:1)

好的,我明白了。使用if(data !== null)代替if (data.trim() != '')

相关问题