【问题标题】:JSON is null but data passes to success in ajaxJSON为空,但数据在ajax中成功传递
【发布时间】:2016-08-08 16:43:59
【问题描述】:

我在 ajax 中遇到了问题。场景是:我想验证用户在输入电子邮件时是否可用。所以我在 javascript 中创建了一个函数来使用其中的 Ajax 脚本来执行此操作。 这是我的代码:

$('#username').keyup(function () {
  var email = $(this).val();

  $.ajax({
    type: 'GET',
    url: 'http://localhost:8080/MeublesTunisv4/web/app_dev.php/email-verification/' + email,
    dataType: "json",
    beforeSend: function () {
      $('#email_status').html('<img id="loading" src ="{{ asset('bundles/theme_front_end/images/loading.gif')}}"></img>');

    },
    success: function (data) {
      $('#email_status').remove();
      $('#email_status').html('<img id="loading" src ="{{ asset('bundles/theme_front_end/images/green_tick.png')}}"></img>');
    }

  });
});

我的问题是:当我输入任何单词时,它会调用 keyup 函数,即使数据为空,它也会成功。我想让它只有在数据正确完成的情况下才能成功。 谢谢。

【问题讨论】:

    标签: javascript ajax


    【解决方案1】:

    尝试关注..希望它能如您所愿...

    $('#username').keyup(function () {
                var email = $(this).val();
    
               if(email != "") {
    
                $.ajax({
                    type: 'GET',
                    url: 'http://localhost:8080/MeublesTunisv4/web/app_dev.php/email-verification/' + email,
                    dataType: "json",
                    beforeSend: function () {
                        $('#email_status').html('<img id="loading" src ="{{ asset('bundles/theme_front_end/images/loading.gif')}}"></img>');
    
                    },
                    success: function (data) {
    
                       // Check response data...
                       if(data == 'true') { 
    
                           $('#email_status').remove();
                           $('#email_status').html('<img id="loading" src ="{{ asset('bundles/theme_front_end/images/green_tick.png')}}"></img>');
    
                        }
    
                    }
    
                });
             }
    
        }); 
    

    【讨论】:

    • 我不认为data字面上"null",而是一个空值,例如一个空字符串。否则,这个答案和我的一样。
    • 对不起...但我只是假设如果没有找到记录,则响应可能为空或假(任何令牌)..
    • 谢谢#Nikhil 它可以工作,但我修改了一些代码:if (data.email != null)。我的 json 是:{'email':'emailValue'}。所以我比较电子邮件是否为空。谢谢
    【解决方案2】:

    在做任何事情之前尝试一些错误检查。因此,success 回调会被调用(不能有条件地停止),但里面的代码会被阻止。

    使用以下内容封装success 事件处理程序中的所有内容,以便它仅在data 不为空(空字符串)时执行:

    if(data != "") {
        // action here
    }
    

    我不确定您所说的“数据为空”是什么意思,因此如上所示的简单空字符串条件可能不足以检查数据是否为空。这将简单地检查data 参数是否为空。

    【讨论】:

    • 感谢 lambda Ninja 也帮助我解决了问题
    猜你喜欢
    • 2015-07-29
    • 2012-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-17
    • 2014-01-29
    • 2011-08-05
    • 2012-10-16
    相关资源
    最近更新 更多