douying8666 2017-04-04 07:36
浏览 39
已采纳

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

Below I have a JSON array in my main PHP file. As you can see $firstname_error and $lastname_error are variables which I intend to pass to AJAX in order to have it displayed in two separate divs. At the moment nothing shows up and am unsure why. Any insight is greatly appreciated.

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 and .error5 currently displays nothing.

展开全部

  • 写回答

3条回答 默认 最新

  • douhuiwan5141 2017-04-04 08:08
    关注

    Since you have dataType: 'json', the data variable passed to your success function is going to be an object so you can't use trim().

    To check if the value exists in the response you can use hasOwnProperty on data:

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

    Hope this helps!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部