onclick执行php函数,而无需重新加载页面

时间:2019-12-04 23:13:43

标签: javascript php jquery ajax

我有一个php代码,其中显示一个警告框,单击“确定”或“取消”,如果我单击“确定”,它将跳转到执行php函数以删除该图像的链接

<?php 
//echo $pictures['binId'];

if(count($other_images))
{
  foreach($other_images as $nimg)
  {
    $get_images=$this->Common_model->newgetRows('StorageFile',array('binId'=>$nimg['id'],'name'=>'large'));
    $nimage_urls=Image_path .$get_images[0]['binId']."/".$get_images[0]['hash'].".".$get_images[0]['extension'];
    if(count($get_images)){
?>
      <div class="col-xs-4">
        <a class="postimgsd"
            onclick="return confirm('Are you sure, want to delete this image?');" 
            href="<?php echo base_url('Home/deletePostimage/'.$get_images[0]['binId'].'/'.$value['id'].'') ?>">
          <span class="close">X</span>
          <img src="<?php echo $nimage_urls; ?>" >
        </a>
      </div>
<?php
    } 
  }
}
?>

image1 image2

deletePostimage是php文件中的一个函数,用于删除所选的图像

如何在不重新加载页面的情况下删除图像?

1 个答案:

答案 0 :(得分:1)

您需要使用AJAX,如先前的评论所述。我已经用注释编写了所需的代码。您还需要一个单独的php脚本来删除我也包含的图像(delete_image.php)。

我没有使用内联onclick事件,而是使用jquery制作了事件侦听器。它将应用于所有具有“ postimgsd”类的链接。

代码如下:

<?php 
//echo $pictures['binId'];

if(count($other_images))
{
  foreach($other_images as $nimg)
  {
    $get_images=$this->Common_model->newgetRows('StorageFile',array('binId'=>$nimg['id'],'name'=>'large'));
    $nimage_urls=Image_path .$get_images[0]['binId']."/".$get_images[0]['hash'].".".$get_images[0]['extension'];
    if(count($get_images)){
?>
      <div class="col-xs-4">
        <a class="postimgsd"

            href="<?php echo base_url('Home/deletePostimage/'.$get_images[0]['binId'].'/'.$value['id'].'') ?>">
          <span class="close">X</span>
          <img src="<?php echo $nimage_urls; ?>" >
        </a>
      </div>
<?php
    } 
  }
}
?>
     <div id="response_container">
        <!-- AJAX Response will appear here-->
    </div>
<!-- include jQuery, you can remove this line if you have already included it-->
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"
        integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
    <script>
        function delete_image(image_name) {
                var url = 'http://localhost/delete_image.php'; //URL to delete_image PHP Script
                var response_container_id = 'response_container';// ID of div Where the response message will be shown

                $.ajax({
                    url: url,
                    type: 'POST', //POST or GET
                    async: true,
                    data_type: 'html',
                    data: {
                        'image_name': image_name //Data for the request
                    },
                    success: function (response) {
                        $('#' + response_container_id).html(response); //put the resonse in the resposne container, you can delete this line if you don't want to show a reponse or you can add additonal logic
                    },
                    error: function (jqXHR, exception) {

                        var msg = '';
                        if (jqXHR.status === 0) {
                            msg = 'Not connected. Verify Network.';
                        } else if (jqXHR.status == 404) {
                            msg = 'Requested page not found. [404]';
                        } else if (jqXHR.status == 500) {
                            msg = 'Internal Server Error [500].';
                        } else if (exception === 'parsererror') {
                            msg = 'Requested JSON parse failed.';
                        } else if (exception === 'timeout') {
                            msg = 'Time out error.';
                        } else if (exception === 'abort') {
                            msg = 'Ajax request aborted.';
                        } else {
                            msg = 'Uncaught Error.' + jqXHR.responseText;
                        }
                        $('#' + response_container_id).html(msg);
                        console.log(msg);

                    }
                });
            }

            //when the document finishes loading
            $(document).ready(function () {
                var link_class = 'postimgsd';

                // onclick event for every link that has class of the link_class (postimgsd)
                $('a.' + link_class).on('click', function (e) {
                    //get the image name from the image tag thats inside the link
                    var image_name = $(this).children('img').attr('src');                   
                    if (confirm('Are you sure, want to delete this image?')) {
                        delete_image(image_name);
                    }
                });
            });
            //Reading:
            /*
            jQuery

            .children()
                https://api.jquery.com/children/

            .ready()
                https://api.jquery.com/ready/

            .ajax()
                https://api.jquery.com/jquery.ajax/
            */
    </script>

在delete_image.php文件中,您需要这样的内容:

<?php
if(isset($_POST['image_name'])){
    //delete image code
    deletePostimage();
    echo "image removed";
}else{
    echo "no image file name";
}

function deletePostimage(){
    //your delete function code
}
 ?>

如果您有任何疑问,请告诉我。