【问题标题】:Using onchange to send get requests to API使用 onchange 向 API 发送 get 请求
【发布时间】:2015-03-25 02:36:31
【问题描述】:

我有一个注册表单,用户在其中添加了他们的postcode,然后通过向 API 发送GET 请求,我收到并在下面的字段中显示address

我的问题是我目前在 form_tag 本身中使用onchange: "getAddress(this.value)",但是我想使用 jQuery 事件处理程序来实现它。这就是我在页面底部<script> 标记中的代码的样子:

var getAddress = function(postcode) {
    $.ajax({
        url: '<%= get_address_url %>',
        dataType: 'script',
        type: "GET",
        data: { postcode: postcode }
  });
};

$(document).ready(function() {
    dooo();
    $(this).on("change", "input", dooo);
    var p = $("input#jobseeker_postcode");
    $(this).on("change", "input#jobseeker_postcode", getAddress(p.val()));
}); 

doo() 函数在我的 .js 文件中声明,管理它的事件处理程序就像一个魅力。但是我没有设法让邮政编码的东西(代码中的第二个事件处理程序)运行。我发现该字段的值没有正确检索,因为无论我填写什么,我都会从 API 中得到一个 failed response => 我传递的 value""

仅供参考,doo() 函数实现了一个 jQuery UI 进度条,该进度条根据填写的字段数进行加载。

【问题讨论】:

  • on 需要一个函数。您应该更改 getAddress 以便它返回一个函数。

标签: javascript jquery ruby-on-rails-4


【解决方案1】:

您应该将更改事件处理程序设置为一个函数。由于您需要将参数传递给处理函数,因此应在closure 中定义它。

这应该可行:

var getAddress = function(postcode) {
    return function() {
      $.ajax({
        url: '<%= get_address_url %>',
        dataType: 'script',
        type: "GET",
        data: { postcode: postcode }
      });
    };
};

【讨论】:

  • 这似乎解决了触发问题。它现在可以正确触发,但它仍然返回一个值 "",因此告诉我邮政编码不存在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多