在Ajax响应后显示弹出警报

问题描述 投票:0回答:3

我在此代码中使用ajax使用post方法获得了JSON请求

$(document).ready(function() {
  $(document).on('submit', '#registration_check', function() {
    var data = $(this).serialize();
    $.ajax({
      type: 'POST',
      url: 'apidomain.com',
      data: data,
      success: function(data) {

        $("#registration_check").fadeOut(500).hide(function() {
          $(".result_1").fadeIn(500).show(function() {
            $(".result_1").html(data);
          });
        });
      }
    });
    return false;
  });
});

响应将在此元素上返回3个字段,如姓名,电子邮件,电话:

<div id="result_1"></div>

它到目前为止工作得很好,但是我想要做的是我想显示警报或弹出消息,如果ajax响应发现一些返回值为null。例如:

  1. 如果JSON响应返回:name:jhon,email:jhon @ doe.com,phone:123456789用户将重定向到另一页(到目前为止完成)
  2. 但如果JSON响应返回名称:jane,电子邮件:jane @ doe.com,电话:

弹出或警报将出现,文本电话号码为空。

javascript php json ajax
3个回答
0
投票

我想到的第一件事是:你是否需要在文档元素中使用JSON响应,或者是,你不知道如何使用jQuery Ajax?

无论如何,这个解决方案应该在两种情况下帮助你:

$(document).ready(function()
{   
    $(document).on('submit', '#registration_check', function()
    {       
        var data = $(this).serialize();
        $.ajax({
        type : 'POST',
        url  : 'apidomain.com',
        data : data,
        dataType: 'json', // tell jQuery, that the response data will be a JSON - it will be parsed automatically
        success :  function(data)
                   {
                        // now you have a parsed JSON object in the 'data' var

                        var show_alert = false;

                        if (data.phone === null || !data.phone.length) {
                            show_alert = true;
                        }

                        if (data.email === null || !data.email.length) {
                            show_alert = true;
                        }

                        if (show_alert) {
                            alert('here is the alert :)');
                        }

                        $("#registration_check").fadeOut(500).hide(function()
                        {
                            $(".result_1").fadeIn(500).show(function()
                            {
                                $(".result_1").html(JSON.stringify(data));
                            });
                        });

                   }
        });
        return false;
    });
});

1
投票

如果您的数据是JSON对象,那么您可以执行以下操作:

success: function(data) {
  for (var i in data) {
    if (!data[i]) {
      alert(/* MESSAGE HERE */)
      return;
    }
  }

  // Your regular code here
}

1
投票

您可以在php文件中创建值的关联数组,并以json格式回显它

echo json_encode($array);

然后你会在这样的ajax响应中收到这个

  var objs = JSON.parse(data);

然后你可以通过像你在php文件中的关联数组中定义的nameemailphone这样的键来解析值

console.log(objs.name);
console.log(objs.email);
console.log(objs.phone);

这是您可以单独解析值的方法。您也可以按自己的方式申请条件

© www.soinside.com 2019 - 2024. All rights reserved.