繁体   English   中英

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

[英]How can I pass parameters from page1.html to server.php and return results to page2.php using 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>

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

首先,您想将所有[input]元素放在表单上。

<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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM