繁体   English   中英

Javascript - axios 请求后脚本不起作用

[英]Javascript - Script doesn't work after axios request

在我的项目中,我使用axios来方便 Ajax 请求。 我创建了一个脚本,在其中向所有链接添加了一个侦听器,然后感谢 Axios,我发出了 Ajax 请求。 我想在 Ajax 请求之后进行处理。 我做了一些测试,代码很好。 但是一旦我用axios把它放在 then () 函数中,代码就不再工作了

这是我的PHP代码

<tr class="table-light">
  <td>
    <a href="{{path('notification_read', {'id': notif.id})}}" class="btn btn-link js-read" title="Marquer comme lu">
      <i class="fas fa-dot-circle" style="color: Dodgerblue;"></i>
    </a>
  </td>
</tr>

JS

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<script>
  function onClickBtnRead(event) {
    event.preventDefault();
    const url = this.href;
    var tr = $(this).closest("tr").get(0);
    $(tr).removeClass('table-light');

    this.href = '#';
    $(this).addClass('disabled');
    $(this).removeAttr('title');

    var i = $(this).children();
    $(i).css('color', '#D3D3D3');

    axios.get(url).then(function(response){
      console.log(response);
    });
  }

  document.querySelectorAll('a.js-read').forEach(function(link){
    link.addEventListener('click', onClickBtnRead);
  });
</script>

像这样,它可以工作,但我想将我的代码放入 then() 函数中,如下所示:

function onClickBtnRead(event) {
  event.preventDefault();
  const url = this.href;

  axios.get(url).then(function(response) {
    console.log(response);
    var tr = $(this).closest("tr").get(0);
    $(tr).removeClass('table-light');

    this.href = '#';
    $(this).addClass('disabled');
    $(this).removeAttr('title');

    var i = $(this).children();
    $(i).css('color', '#D3D3D3');
  });
}

Ajax 请求有效,但不再考虑之后的处理

(对不起我的英语,我使用翻译,因为我是法语)

您是否尝试过使用钩子而不是函数?...我不知道究竟是什么问题。 在我必须实现 Axios 的那天,我在这里使用了以下代码:

// execute simultaneous requests 
axios.all([
  axios.get('https://api.github.com/users/mapbox'),
  axios.get('https://api.github.com/users/phantomjs')
])
.then(responseArr => {
  //this will be executed only when all requests are complete
  console.log('Date created: ', responseArr[0].data.created_at);
  console.log('Date created: ', responseArr[1].data.created_at);
});

也许在then函数中,您可以对请求的数据进行处理。

如果您想查看更多信息,我发现有用的来源是: https : //blog.logrocket.com/how-to-make-http-requests-like-a-pro-with-axios/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM