【问题标题】:Javascript - Script doesn't work after axios requestJavascript - axios 请求后脚本不起作用
【发布时间】:2020-04-08 20:24:54
【问题描述】:

在我的项目中,我使用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 请求有效,但不再考虑之后的处理

(对不起我的英语,因为我是法国人,所以我使用翻译器)

【问题讨论】:

  • 然后在里面记录下this的值,看起来“this”是问题,上下文问题......
  • 好的,现在可以了,谢谢!
  • 出了什么问题?

标签: javascript php ajax request axios


【解决方案1】:

您是否尝试过使用钩子而不是函数?...我不知道究竟是什么问题。在我必须实现 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/

【讨论】:

    猜你喜欢
    • 2018-05-20
    • 2018-12-25
    • 2019-09-28
    • 2018-12-28
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2012-12-23
    相关资源
    最近更新 更多