【发布时间】: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