为什么在ajax请求后未加载`head`文件

时间:2019-01-16 11:54:31

标签: php jquery ajax echo

要从php脚本发送回显,我使用ajax。回显来自类echo的div中。下面是我的html结构:

<body>
<div class="container-fluid">
   <div class="header-fixed">
       <div class="echo"><!-- in here coming the echos from php --></div>

我的ajax看起来像这样:

$.ajax({
            url: "actions.php",
            type: "POST",
            data:  new FormData(this),

            contentType: false,
            processData: false,
            success: function(data) {
            $(".echo").html(data);          

            },

       });

这是我的php脚本 actions.php

if($_POST['deletefile']) {
     unlink($_POST['deletefile']);
     echo  '<span class="closebtn">CLOSE</span><br />';
     echo basename($_POST['deletefile']) . ' successful deleted';
     echo '<script>
           $('.closebtn').click(function(){
           $(this).parent('.echomessage').fadeOut(500);
           });
           </script>';  
}

问题:回声中的小js需要head中的jquery核心文件。但是似乎他再也没有被加载,因为当单击“关闭”按钮时,回声不再消失了。

也将核心文件放入回显中,如下所示:

echo '<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>';

工作正常。但是我想这不是应该的。 我如何解决这个问题而又不用在回显中再次发送核心文件?因为它已经在head加载中...

2 个答案:

答案 0 :(得分:2)

其中注入HTML的元素是<div class="echo">,其中jQuery代码正在搜索其他内容:

$(this).parent('.echomessage')
//              ^---- should be ".echo" 

话虽如此,我建议您修改服务器端脚本以返回JSON编码的响应,并在success事件内部移动显示它的逻辑,如下所示:

$.ajax({
    url: "actions.php",
    type: "POST",
    data: new FormData(this),
    success: function(response) {
        // response could be something like {"success": true, "message": "aaa.txt deleted"}
        $("<span class='closebtn'>CLOSE</span>")
            .appendTo(".echo")
            .after("<br>", response.message)
            .on("click", function() {
                $(this).parent(".echo").fadeOut(500);
            });
        $(".echo").html(data);
    },
});

答案 1 :(得分:0)

那呢:

 success: function(data) {
          $.getScript( "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" ); //load core file
          $(".echo").html(data);          

        },