我遇到了异步 Ajax 调用在 Safari 中无法工作的问题。它适用于所有其他浏览器,但不适用于 Safari。仅当我们在按钮或 anchor 上有重定向/链接并单击该链接来调用 Ajax 函数时,这才会出现问题。
我在下面创建了一个非常简单的示例:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Ajax issue is Safari</title>
<script src="//code.jquery.com/jquery-2.2.3.js"></script>
<script>
$( document ).ready(function() {
$('#mybutton').click(function(){
$.ajax({
type: "POST",
dataType: "text",
async: true,
url: "dosomething.php",
error: function(a,b,c){
alert("Ajax Error");
},
success: function(data){
alert(data);
},
});
});
});
</script>
</head>
<body>
<a href="page2.php" id="mybutton">Click here</a>
</body>
</html>
dosomething.php 在哪里
<?php
echo "Success. Click ok to be redirected.";
?>
此示例的实时版本如下:http://visionfactor.com.au/ajax-safari/
虽然有一个 href=,但 Ajax 总是会抛出错误。一旦我删除 href 它就会起作用。如果我使用按钮而不是 anchor 并使用 Javascript 进行重定向,情况也是如此。重定向到位时结果相同。
现在我意识到我可以将重定向放入 Ajax 成功回调中,但是我不想这样做,因为这似乎没有必要,因为它应该像所有其他浏览器一样在 Safari 中以其他方式工作。另外,在我的现实世界(非简化)代码中,执行此操作非常困惑,因为我对多个链接/按钮具有相同的类,因此它们都执行相同的 Ajax,但随后每个都重定向到不同的位置。因此,我必须传递一些其他值,例如另一个类,以便定义特定于该链接的相关重定向......就像我说的困惑。
如何让这个非常简单的代码在 Safari 中工作?
谢谢, 妮可
最佳答案
尝试添加 preventDefault
像这样:
$( document ).ready(function() {
$('#mybutton').click(function (event) {
event.preventDefault(); // stop the click to redirect to the URL in href
$.ajax({
type: "POST",
dataType: "text",
async: true,
url: "dosomething.php",
error: function(a,b,c){
alert("Ajax Error");
},
success: function(data){
alert(data);
},
});
});
});
关于javascript - 异步 Ajax 无法在带有重定向的 Safari 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39953634/