新手问题 诡异的问题 data-remote 邦定 Ajax 事件回调函数中 参数 undefinde

wu · August 06, 2017 · Last by wu replied at August 07, 2017 · 1319 hits

erb 中的代码

<a class="option option-equal" href="/articles/22/action" data-remote="true" data-method="post" id="article_top"></a>
<script type="text/javascript" charset="utf-8">
  $(function () {
      $("#article_top").on("ajax:before", function (e) {
         if (PageValue.user_id == ""){
             return false;
         }
      }).on("ajax:beforeSend", function (e, xhr, options) {
          alert("beforeSend")
          alert("xhr " + xhr)
          alert("options " + options)
      }).on("ajax:success", function (e, xhr, status, err) {
          alert("success");
          alert("event: " + e)

          alert("xhr : " + xhr)
          alert("status : " + status)
          alert("data : " + err)

      })

  })

</script>

点击 a 标签 会调用 ajax 事件,为什么除了 e 是 Event 对象外,其他参赛都是 undefinde。

我 debug,看了 ujs 的源代码

beforeSend: function(xhr, options) {
            if (fire(element, 'ajax:beforeSend', [xhr, options])) {
              return fire(element, 'ajax:send', [xhr]);
            } else {
              fire(element, 'ajax:stopped');
              return xhr.abort();
            }
          }
fire = Rails.fire = function(obj, name, data) {
        var event;
        event = new CustomEvent(name, {
          bubbles: true,
          cancelable: true,
          detail: data
        });
        obj.dispatchEvent(event);
        return !event.defaultPrevented;
      };

这里 obj.dispatchEvent(event); 调用事件时只参进了一个额 event 参数

文档里是这么写的。

事件名 额外参数 触发时机
ajax:before 在整个 Ajax 调用开始之前,如果被停止了,就不再调用。
ajax:beforeSend xhr, options 在发送请求之前,如果被停止了,就不再发送。
ajax:success xhr, status, err Ajax 调用结束,返回表示成功的响应时。

请问是什么原因我在回调函数里没有接收到参数?

2 Floor has deleted

感谢!我用的是最新的 rails

You need to Sign in before reply, if you don't have an account, please Sign up first.