【问题标题】:Ajax callback after php executedphp执行后的Ajax回调
【发布时间】:2015-05-20 21:48:32
【问题描述】:

我想使用插件 sweetalert 显示警报消息。 我的页面显示在索引页 10 产品上 每个都有链接(可能是带有隐藏字段的表单),其中包含要发送到 php 脚本的数据

例如 script.php?id=x&b=x&c=z

PHP 有 HTML

<?php foreach($datas as $data): ?>
<a href="auction_buy.php?id=<?php echo $data->$id; ?>&b=x&c=z" class="a">link</a>
<?php endforeach; ?>

$datas 是来自数据库的数据对象

现在如果我添加 ajax

$('.a').click(function (event){ 
event.preventDefault(); 
$.ajax({
    url: $(this).attr('href')
    ,success: function(response) {
       swal("Here's a message!"); 
       //Similar to alert(''); i tried alert too but it didnt work
    }
})
return false;
});

并且 alert('ok') 或 swal alert 不会出现。 我有产品说明页面,其中与表单数据类似的代码有效 那么多个链接可能有问题吗?

产品描述中有效的代码

jQuery("#contactForm1").ready(function() {
var frm = $('#contactForm1');
frm.submit(function (ev) {
    $.ajax({
        type: frm.attr('method'),
        url: frm.attr('action'),
        data: frm.serialize(),
        success: function (data) {
           swal({  
                title: "Success!", 
                text: "Code worked",
                type: "success",
                confirmButtonColor: "#4B77BE", 
                confirmButtonText: "Ok",
                closeOnConfirm: true 
            },
                function() {
                    location.reload();
                }
            );

        }
    });

    ev.preventDefault();
});

});

我需要的是在 ajax 函数之前或之后显示警报。 我真的花了很多时间来解决这个问题,但是我是 jquery 的初学者,有人可以帮我吗?非常感谢,抱歉英语不好:)

【问题讨论】:

  • js解析新行,所以'success'之前的","必须在url:bla bla行的and处。如果还是不能解决,请检查 1. js中是否报错? (如果您使用 firefox 或 chrome 并重新加载页面并检查“all”/“errors”选项卡,请按 f12),2. 如果请求已发送,它返回什么(检查“net”选项卡)。跨度>
  • ev.preventDefault();将在 ajax 调用之前执行,因此您无法收到警报消息

标签: javascript php jquery html ajax


【解决方案1】:

试试这个:

$('.a').click(function (event){
  $.ajax({
   url: $(this).attr('href')
   })
   .done(function(response) {
        swal("Here's a message!"); 
    )};
  //it should be here after ajax
  event.preventDefault(); 
});

您应该在最后声明 event.preventDefault()。另外请记住,从 jQuery 1.8 开始不推荐使用成功回调,您应该使用 done()。

【讨论】:

    猜你喜欢
    • 2023-03-11
    • 2020-07-19
    • 1970-01-01
    • 2017-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    相关资源
    最近更新 更多