发送自动完成的AJAX请求

时间:2016-01-05 12:44:08

标签: javascript jquery

我想在jquery中使用autocomplete,因为我在页面上发送请求以获取数据,但这对我不起作用。请帮助我

的jQuery

var addInput = function() {
  var inputHTML = "<input name='search' value='' class='test' maxlength='20' />";
  $(inputHTML).appendTo("form#myForm");
  $("input.test:last").focus();
};

$("input#addButton").click(addInput);
var options = {
  source: "abc.html",
  minLength: 2
};

$(document).ready(function() {
  $(".test" ).on('focus', function() {
    $(this).autocomplete(options);
  });
});

2 个答案:

答案 0 :(得分:0)

请参阅我所说过的行中的错误。

var addInput = function() {
  var inputHTML = "<input name='search' value='' class='test' maxlength='20' />";
  $(inputHTML).appendTo("form#myForm");
  $("input.test:last").focus();
};
$("input#addButton").click(addInput);
}); // This is wrong. It should be }

var options = {
  source: "abc.html",
  minLength: 2
};
$(document).ready(function() {
  $(".test" ).on('focus', function() {
    $(this).autocomplete(options);
  });
});

只需删除以上行,即:

var addInput = function() {
  var inputHTML = "<input name='search' value='' class='test' maxlength='20' />";
  $(inputHTML).appendTo("form#myForm");
  $("input.test:last").focus();
};
$("input#addButton").click(addInput);

var options = {
  source: "abc.html",
  minLength: 2
};
$(document).ready(function() {
  $(".test" ).on('focus', function() {
    $(this).autocomplete(options);
  });
});

如果上述操作失败,请尝试以下操作:

$(document).ready(function() {
  $(".test" ).on('focus', function() {
    $(this).autocomplete({
      source: "abc.html",
      minLength: 2
    });
  });
  $("input#addButton").click(function () {
    var inputHTML = "<input name='search' value='' class='test' maxlength='20' />";
    $(inputHTML).appendTo("form#myForm");
    $("input.test:last").focus();
  });
});

答案 1 :(得分:0)

我在这里看到了什么问题:

  1. 您正准备在dom准备好之前绑定事件。
  2. 你有一个额外的未知结束标记。
  3. 您正在绑定一个不在DOM中但在用户交互之后的元素上的事件。
  4. 我可以在这里看到额外的结束:

    $("input#addButton").click(addInput);
    }); // <----------------------------------this one don't know which one
        //------------------------------------but it should not have to be here.
    

    另外我建议你这样使用它:

    var addInput = function() {
      var inputHTML = "<input name='search' value='' class='test' maxlength='20' />";
      var options = {
        source: "abc.html",
        minLength: 2
      };
      $(inputHTML).appendTo("form#myForm");
      $("input.test:last").focus().autocomplete(options); // <----initialize it here.
    };
    
    
    $(document).ready(function() {
      $("input#addButton").click(addInput); // bind the event here.
    });