如何将page1.html中的参数传递给server.php并使用ajax将结果返回给page2.php?

时间:2015-01-05 05:55:07

标签: php jquery ajax

我有一个myfiles.php页面,它扫描目录并显示一个文件列表,每个文件旁边都有一个单选按钮,我有一个加载按钮,将所选文件的名称发送到server.php,后者从中获取数据该文件并将其发回。
我的问题是我不希望将结果发送回myfiles.php,而是希望将结果发送回来,浏览器将我带到editor.php。

Myfiles.html:

<table>
<form>
<?php 
$dir    = "./userFiles/".$login;
$files = array_diff(scandir($dir), array('..', '.')); 
foreach($files as $ind_file){ 
?> 
<tr><td><input type="radio" name="files" value="<?php echo $ind_file;?>"></td>
<td><a href="<?php echo $dir."/".$ind_file;?>"><?php echo $ind_file;?></td></tr>
<?php 
} 
?> 
</form>
</table>
<br/><button id="load">load</button>
<script>
$("#load").click( function() {
    $.ajax({
        url : server.php,
        type: 'post',
        data : {
            filename : $("input[name=files]:checked").val(),
            action : 'load'
        },
        success : function(html) {
           editor.setValue(html);
        }
    });
});

server.php:

$this->dir = "userFiles";
$this->filename = isset($_POST['filename']) ? $_POST['filename'] : false;
 private function load() {
        $content = @file_get_contents($this->dir.$this->filename);
        echo $content;
    }

Editor.php

<textarea id="code" name="code" autofocus></textarea>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById('code'), {
    mode: 'text/html',
    tabMode: 'indent',
    lineNumbers: true,
    lineWrapping: true,
    autoCloseTags: true
});
</script>

请帮助修改代码以解决我的问题。谢谢。

1 个答案:

答案 0 :(得分:0)

首先,您要将所有[输入]元素放在表单上。

<form name="load" action="<YOUR PHP SCRIPT>" method="post">

<?php 
$dir    = "./userFiles/".$login;
$files = array_diff(scandir($dir), array('..', '.')); 
foreach($files as $ind_file){ 
?> 
<tr><td><input type="radio" name="files" value="<?php echo $ind_file;?>"></td>
<td><a href="<?php echo $dir."/".$ind_file;?>"><?php echo $ind_file;?></td></tr>
<?php 
} 
?> 
<input type="submit" value="Load">
</form>

可以组合Server.php和Editor.php。 您的PHP将如下所示:

<?php
$selectedfile = $_POST['files'];
$content = file_get_contents("<YOUR DIRECTORY>" . $selectedfile);
?>

现在你可以将$ contents注入你的html

<HTML>

<div><?php echo $contents; ?></div>

</HTML>