douxian7117 2013-01-03 15:57
浏览 74
已采纳

如何在按钮点击时复制文件?

I want to build a one page utility/prototype that will do the following:

provide the admin user with a drop down box. when they select an option and then click on a submit button, i want to be able to COPY a file from /var/www/mysite/abc.txt to /var/www/mysecondsite/abc.txt

I've written the php / html to display the form, but can I use jquery/ajax to call a function on the same php file?

Here's my code:

<?php

$listofcountries='';

echo "<h2>Select a site</h2>";
echo " <script src='http://myserver/myapp/assets/js/jquery-1.8.1.min.js'></script>";

if ($handle = opendir(dirname(__FILE__)."/secrets/")) {

  echo "<input type=text list=site >";
  echo "<datalist id=site >";

    /* This is the correct way to loop over the directory. */
    while (false !== ($entry = readdir($handle))) {
    //ignore temporary files, and directories.
    if ( (strpos($entry, "~") === false) && !(trim($entry)==".") && !( $entry=="..") ){
          //echo "$entry
<BR>";
          $country=getCountryName($entry);
          echo "<option>".$country;
      }
    }
    }
    closedir($handle);

echo "</datalist>";
echo "<input type=submit id='changert'><BR>";
echo "<script>";
echo "$(document).ready(function(){";

echo "       $('#changert').live('click', function()  {";
echo "      alert('in the changert function'); ";
echo "      });";

echo "  }); "; //end document ready
echo "</script> "; //end javascript



function getCountryName($fileame)
{
    $pattern = '/([a-z]*).([a-z]*).([a-z]*).php/i';
    preg_match_all($pattern, $fileame, $matches, PREG_SET_ORDER);           
    foreach ($matches as $match) {

        return $match[1];
    }
}

in the real version, this solution will be part of a codeigniter solution... so i'll have a proper MVC. But for now, I'd like to be able to contain all the logic in one file. Can you tell me how i can do this?

  • 写回答

3条回答 默认 最新

  • doulang1945 2013-01-03 16:00
    关注

    jQuery is just JavaScript so it's all on the client. Any server-side file copying would still need to be handled by your PHP. Simplest solution is just to make an AJAX request on button click which hits your PHP API and passes a token or something so non-session users aren't copying files maliciously.

    $('#myButton').on('click', function(e) {
    
        $.ajax({
            url  : '/copyFile.php',
            data : {
                fileName : $('#mySelectMenu').val(),
                token    : someTokenYourPHPInjectedIntoYourJS
            },
            type : 'POST',
            success : function (data) {
                // yay
            }
        });
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?