我有一段代码,其中有一个链接和一个输入按钮,它们都调用相同的onclick函数。然而,他们的行为却不同。
<input type="button" onclick="undelete_this("profile.php", 42)" value="Undelete">
<a href="" onclick="undelete_this("profile.php",42)"><strong>here</strong></a>
function undelete_this(url, id){
if(confirm("Are you sure you want to undelete this record?")){
if(id!=="" && id!=0){
var info = 'id=' + id +"&action=undelete";
$.ajax({
type: "GET",
url: url,
data: info,
success: function(){
window.location.href = ($(location).attr('pathname')+"?enter=false&id="+id);
},
error: function(jqXHR, exception, realexception) {
alert(jqXHR.responseText+" "+realexception);
}
}
)
}
}
return false;
}单击按钮时,ajax状态是成功的;但单击链接时,ajax状态为错误(错误代码= 0),responseText为空。
有人知道为什么会发生这种事吗?
发布于 2014-01-10 14:51:15
因为有一个空的href会导致在单击链接时重新加载页面。重新加载页面(通常:导航到任何URL)将中止任何未完成的AJAX请求,这就是您没有得到响应的原因。
可能的解决办法:
onclick="undelete_this("profile.php",42); return false;"将取消默认操作(重新加载页面)href="javascript:;"将使默认操作变为无操作,再次防止重新加载页面。发布于 2014-01-10 15:06:15
不能简单地将href保留为空,因为href=''是指向当前页面的链接(即它会导致页面刷新)。
有一种方法可以让链接在点击时什么也不做(除非Javascript事件被绑定到它)。
<a href="javascript:undelete_this("profile.php",42);"><strong>here</strong></a>https://stackoverflow.com/questions/21047259
复制相似问题