首页 > 解决方案 > Jquery Autocomplete Load Data at once ($.ajax vs $.get/$.post)

问题描述

Somebody please help, really curious about this.

I want autocomplete only get data source only once at page load. I've tried two ways.

First, with $.ajax(GET/POST) and it was successful

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

Second way, with $.post/$.get but failed

//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
  });

});

Any idea why $.post/$.get fail ? Is there somethin wrong with my $.post/$.get ? Or whether this way can't be used in this case ?

Thnks & Brgds

标签: jqueryhtmlajaxautocomplete

解决方案


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

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

推荐阅读