Jquery 立即自动完成加载数据 ($.ajax vs $.get/$.post)

Jquery Autocomplete Load Data at once ($.ajax vs $.get/$.post)

有人请帮忙,真的很好奇这个。

我希望自动完成仅在页面加载时获取数据源一次。我试过两种方法。

首先用$.ajax(GET/POST)成功了

$.ajax({
  type: "GET",
  url: "search.php",
  data: {
    action: 'getCoa'
  },
  dataType: "json",
  success: function(data) {
    $('#coa').autocomplete({
      source: data
    });
  },
  error: function(result) {
    alert("Error");
  }
});

第二种方式,$.post/$.get但失败了

//1st try - failed
$.post('search.php', {
  action: 'getCoa'
}, function(result) {
  $('#coa').autocomplete({
    source: result
  });
});


//2nd try - failed
var test = $.post("search.php", {
    action: 'getCoa'
  }, function(result) {
    $('#coa').autocomplete({
      source: result
    });
  })
  .done(function(result) {
    $('#coa').autocomplete({
      source: result
    });
  })
  .fail(function() {
    alert("error");
  })
  .always(function() {
    alert("finished");
  });


//3rd - failed
var coaList = [];
$.get("search.php?action=getCoa", function(data, status) {
  console.log(coaList);
  
  coaList = data;
  $('#coa').autocomplete({
    source: result
  });

});

知道为什么 $.post/$.get 会失败吗?我的 $.post/$.get 有问题吗?或者在这种情况下是否不能使用这种方式?

感谢与支持

您需要在第一个 $.ajax() 中指定的 callback 函数之后的最后一个 $.post() 参数中指定一个 JSON dataType适合您的方法。

$.post('search.php', {
    action: 'getCoa'
}, function(result) {
    $('#coa').autocomplete({
        source: result
    });
}, 'json');