Axios.js - 防止默认()在单击和数据参数似乎关闭时不起作用



所以我当前的代码有很多问题。

首先,我使用 Axios 发送请求,我试图从我的 Symfony 后端获取数据,但是无论我给该方法什么,它总是发送一个 GET 请求。这不是一个"问题",但有这样的行为很烦人,因为它没有做它应该做的事情。如果我将method更改为 POST,它仍然会发送 GET 请求......

然而,更大的问题是我正在使用的preventDefault()函数不起作用,我在链接标签上添加了一个 eventListener,但每次我单击它时,它都会显示从我的后端发送的 JSON 响应......

这是我的代码:

<a id="link" href="{{ path('corrigerExercice', {'id': id}) }}" class="btn btn-primary">Corriger</a>

一个简单的标签。

document.onload = function () {
var link = document.getElementById('link');
link.addEventListener('click', onClickCorrection);
console.log(link);
function onClickCorrection(event) {
event.preventDefault();
const test = this.href;
console.log(test);
axios({
method: 'get',
url: url,
data: 'true'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
};

请注意,console.log(link)console.log(url)没有在控制台中打印任何内容(我使用的是Firefox...我不知道为什么。

此外,我在后端有一个问题,似乎与请求的paraters有关。我正在传递"true"作为data,在我的后端我正在这样做

/**
* @Route("/corrigerExercice/{id}", name="corrigerExercice")
*/
public function corrigerExercice(Exercice $exercice, Request $request): Response
{
$test = $request->query->get('data');
if ($test == "true") {
$message = "Contains true";
} else {
$message = "Does not contain true";
}
$contenu = $exercice->getContenu();
return $this->json(['code' => 200, 'message' => $message, 'contenu' => $contenu], 200);
}

这是我的回复:

code    200
message "Does not contain true"

响应直接显示在浏览器中,而不是控制台中。因此,preventDefault()在这里似乎无法正常工作。

老实说,我很迷茫,不知道为什么这么简单的代码片段没有产生我想要的预期结果。这里的预期结果是,修剪按钮链接不会显示请求,而是将其打印在控制台日志中,请求与数据参数一起发送,我的后端可以正确"分析",这里只是一个基本的字符串比较并发送适当的响应......

有人可以帮助我解决这些问题吗?

我在javascript方面提出了一些问题。(而且我不是专家,但它有效(

  • 事件捕获在 window.onload 上的匿名函数上工作正常
  • 您必须在单击更正上将"this"发送到您的函数
  • 使用 .getAttribute('href'( 获取 'href' 的值

希望它会有用

<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
</head>
<body>
<a id="link" href="https://jsonplaceholder.typicode.com/todos/1" >Corriger</a>
<script  type="text/javascript">

window.onload = function () {
var link = document.getElementById('link');
link.addEventListener('click', function(){
onClickCorrection(this);
});
console.log(link);
function  onClickCorrection(element) {
event.preventDefault();
const href = element.getAttribute('href');
console.log(href);
axios({
method: 'get',
url: href,
data: 'true'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
};

</script>
</body>
<html>

最新更新