问题描述
我有一个
<button id="myid">
在我的HTML代码中。 在我的JS文件中,我尝试捕获click事件并调用特定的URL,就像单击普通的HTML链接一样。
这是我所做的:
$('#myid').on('click', function () {
doSomething();
});
var doSomething = function () {
$.ajax({
url: "/targetURL",
type: "GET",
cache: false,
async: true,
error: function (error) {
console.log(error);
}
});
}
所以-调用了URL,但未显示响应-我猜是因为这是一个ajax调用。 但是我该如何处理呢?
1楼
处理error
函数的方式相同,应该处理success()
函数,该函数将在调用成功完成时触发。
另外,您无需设置async: true
因为默认情况下它设置为true
。
将.preventDefualt()
添加到click
函数中,以确保单击按钮时唯一正在发生的事情就是您要触发的函数。
$('#myid').on('click', function(e) {
e.preventDefault();
doSomething();
});
var doSomething= function(){
$.ajax({
url: "/targetURL",
type: "GET",
cache: false,
success: function(data) {
console.log(data);
}
error: function(error) {
console.log(error);
}
});
}
该data
在参数success()
函数,AJAX返回的数据。
因此,当您登录控制台时,您可以看到该结构,以便以后知道该怎么做。
2楼
Ajax的全部要点是它不会引起导航,而是将响应提供给JavaScript。
如果要导航到新页面,请不要使用Ajax。
使用链接。
如果您希望它看起来像一个按钮,请对其应用CSS。
3楼
要捕获响应数据,您需要添加成功功能,例如错误功能。
var doSomething = function () {
$.ajax({
url: "/targetURL",
type: "GET",
cache: false,
async: true,
success: function(response){
console.log(response);
},
error: function (error) {
console.log(error);
}
});
}
或者,如果您只想打开其他网址(如普通html),则应使用JS窗口对象
var doSomething = function () {
window.open('/targetURL');
}