从AJAX调用服务器响应更新HTML文本和图像

时间:2014-10-31 16:07:40

标签: javascript php jquery ajax

我正在尝试使用javascript从AJAX调用更新我的前端HTML到php页面。我的php页面,如果发送给它的帐户名数据存在与否,则ajax_check_instagram.php返回0或1。我想在用户输入时更新我的​​前端。

我认为一切都是正确的?



$(document).ready(function() { //When the dom is ready 
  $("#instagram").change(function() { //if theres a change in the username textbox
    var acc = $("#instagram").val(); //Get the value in the username textbox
    if (acc.length > 3) { //if the lenght greater than 3 characters
      $("#availability_status").html('<img src="/img/ajax-loader.gif" align="absmiddle">&nbsp;Checking availability...');
      //Add a loading image in the span id="availability_status"

      $.ajax({ //Make the Ajax Request
        type: "POST",
        url: "ajax_check_instagram.php", //file name
        data: "instagram=" + acc, //data
        success: function(server_response) {
          $("#availability_status").ajaxComplete(function(event, request) {
            if (server_response == '0') { //if ajax_check_username.php return value "0"
              $("#availability_status").html('<img src="/img/icon-success.png" align="absmiddle" style="height: 15px; width: auto; margin-top: -2px;"> <font color="#c9dc54" style="padding-top: 5px;"> Confirmed! </font>  ');
              //add this image to the span with id "availability_status"
            } else if (server_response == '1') { //if it returns "1"
              $("#availability_status").html('<img src="/img/icon-error.png" align="absmiddle" style="height: 15px; width: auto; margin-top: -2px;"> <font color="#b11116" style="padding-top: 5px;">Not Valid. </font>');
            }
          });
        }
      });
    } else {
      $("#availability_status").html('<font color="#b11116">Instagram Account Not Found</font>');
      //if in case the username is less than or equal 3 characters only 
    }
    return false;
  });
});
&#13;
<span id="availability_status" class="pull-right" style="padding-right: 5px;">Status</span>
<input id="instagram" name="instagram">
&#13;
&#13;
&#13;

这里还有一个JSFiddle链接!

http://jsfiddle.net/3taudxef/

1 个答案:

答案 0 :(得分:0)

ajaxComplete用于注册Ajax请求完成时调用的处理程序,您已经success函数$.ajax,因此不需要,删除ajaxComplete函数,将您的代码更改为:

 ...
    success: function(server_response){
       if(server_response == '0') { 
            $("#availability_status").html('<img src="/img/icon-success.png" align="absmiddle" style="height: 15px; width: auto; margin-top: -2px;"> <font color="#c9dc54" style="padding-top: 5px;"> Confirmed! </font>  ');
        }  
        else if(server_response == '1') {  
            $("#availability_status").html('<img src="/img/icon-error.png" align="absmiddle" style="height: 15px; width: auto; margin-top: -2px;"> <font color="#b11116" style="padding-top: 5px;">Not Valid. </font>');   
        }    
    });

...

更新 ::如果您希望在每次按键后按ajax调用3,则使用keyup事件代替change事件,如下:

...
$("#instagram").keyup(function() {
...