首页 > 解决方案 > 在自动完成 AJAX 请求中传递参数

问题描述

我正在研究要集成的自动完成选项。自动完成工作正常。但是当我添加另一个参数变量时,自动完成功能不起作用,猜测有点语法问题。在下面附加的脚本中,我需要将变量 countrycode 传递给 fetch_customers.php

$(document).ready(function($) {
  $("#customers").autocomplete({
    var countrycode = '<?php echo $agencyid; ?>';
    data: {
      countrycode: countrycode
    },
    source: "fetch_customers.php",
    minLength: 2,
    select: function(event, ui) {
      var url = ui.item.id;
      if (url != '#') {
        location.href = '/view-customer/' + url;
      }
    },
    // optional (if other layers overlap autocomplete list)
    open: function(event, ui) {
      $(".ui-autocomplete").css("z-index", 1000);
    }
  });
});

标签: jqueryjquery-uijquery-ui-autocomplete

解决方案


您的语法无效。您需要countrycode在您提供给的对象之外进行定义autocomplete()

话虽如此,这不是您在 jQueryUI 自动完成请求中传递数据的方式。相反,您需要在您调用的 URL 的查询字符串中传递值:

$(document).ready(function($) {
  $("#customers").autocomplete({
    source: "fetch_customers.php?countrycode=<?php echo $agencyid; ?>",
    minLength: 2,
    select: function(event, ui) {
      var url = ui.item.id;
      if (url != '#') {
        location.href = '/view-customer/' + url;
      }
    },
    open: function(event, ui) {
      $(".ui-autocomplete").css("z-index", 1000);
    }
  });
});

推荐阅读