如何解决AJAX获取请求按钮
我想在单击按钮时发送一个GET请求,但是我不知道如何将AJAX脚本与按钮连接。
<script>
var url = "http://myurl.com";
var xhr = new XMLHttpRequest();
xhr.open("GET",url);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
}};
xhr.send();
</script>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<button>Make a request</button>
解决方法
您需要将其转换为函数并通过按钮进行调用:
<script>
function call()
{
var url = "http://myurl.com";
var xhr = new XMLHttpRequest();
xhr.open("GET",url);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
}};
xhr.send();
}
</script>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<button onclick="call();">Make a request</button>
,
看到要导入Jquery时,还有一个帮助程序功能可从AJAX请求中获取数据,您可以像这样使用它:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<button>Make a request</button>
<!-- Javascript -->
<script>
$('button').click(function(){
$.get("http://myurl.com",function(result) {
console.log(result);
});
});
</script>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。