douying8666 2017-04-04 15: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 16: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条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?