使用jQuery将javascript变量传递给php

时间:2015-06-25 21:07:21

标签: javascript php jquery

我正在尝试将JavaScript文件变量传递给php以在新窗口中打开文件,但似乎它无法正常工作

JavaScript代码

function Open(){
    var file = prompt("Enter a File name to open with .txt");
    $.get( "php/OpenFile.php",
        file,
        function(result){
            console.log(result);
        }
    );
}

PHP代码

<html>
<body>
<?php
$file = $_GET['file'];

$file2 = file_get_contents($file);

echo "<script type='text/javascript'>window.open($file2)</script>";
?>

</body>
</html>

3 个答案:

答案 0 :(得分:1)

function Open(){
    var file = prompt("Enter a File name to open with .txt");
    $.get( "php/OpenFile.php",
        {file: file},
        function(result){
            console.log(result);
        }
    );
}

在您的Javascript中,您没有使用标识符发送文件名。您可以将Javascript对象{file: file}视为html标记<input name='file' type='text' />

<小时/> 如果您要在新窗口中打开文件,则不需要AJAX。

HTML:

<a href="#" onclick="Open()">Open File</a>

JavaScript的:

function Open() {
    var file = prompt("Enter a File name to open with .txt");
    window.open("php/OpenFile.php?file="+file);
}

这可能;然而,被弹出窗口拦截器阻挡。

答案 1 :(得分:0)

这应该解决它:

function Open(){
    var file = prompt("Enter a File name to open with .txt");
    $.get( "php/OpenFile.php",
        {"file": file}, //    <---------------- Give the variable a name ("file")
        function(result){
            window.open(result); // Open a window with the result
        }
    );
}

<强>的PHP / OpenFile.php

<?php
    $file = $_GET['file'];
    echo file_get_contents($file);
?>

另一种方法是不使用Ajax:

function Open(){
    var file = prompt("Enter a File name to open with .txt");
    window.open(file); // Open the file in a window
}

答案 2 :(得分:0)

您可以通过

打开新窗口(不使用AJAX)
<script>
function openwindow(file_name)
{
window.open("your_script.php?file="+file_name,
    "mywindow","location=1,status=1,scrollbars=1,width=300,height=300");
}
</script>
<a href="javascript:openwindow('test')">open window</a>

your_script.php

<?php
$file = trim($_GET['file']);
$file = preg_replace("/[^A-Za-z0-9]*/",'',$file); 

$full_filename =  'directory/' . $file . '.txt';
if (is_readable($full_filename )) 
  {
  readfile($full_filename);
  }
else die('I can not open file:' . $file); 

&GT;