从javascript发送一个字符串到php(在同一个文件中)

时间:2015-09-23 15:27:33

标签: javascript php ajax

所以基本上,我有一个php文件,我在标题中创建了一个脚本。

在这个脚本中,我使用document.getElementByID两个文本框的值,并将它们连接在一个变量中。但是现在,在同一个脚本中,我想将var发送到php部分以使用它。

我尝试了ajax方式,但由于php和javascript在同一个文件中,因此会出错。

以下是脚本部分的内容:

IN FILE.PHP

<script type="text/javascript">
    rowNum = 0;
    function some_function()
    {    
        var command = "somebasiccommand";

        if(document.getElementById("text_1").value != "" && document.getElementById("text_2").value != "")
        {
            command += " " + document.getElementById("text_1").value + " " + document.getElementById("text_2").value;
        }               

        <?php

            $parameter = command; <----- obviously not working, but that's basically what im looking for

            $output = exec("someExecutable.exe $parameter");

                                (...)
        ?>
    }
</script>

编辑1

所以在这里,我这次试图使用ajax,但这不起作用,好像我想念一些东西。这是server.php:

<?php

$parameter = $_POST['command']; 

$output = exec("someexecutable.exe $parameter");
$output_array = preg_split("/[\n]+/",  $output); 
print_r($parameter);
?>

这是我的client.php中的ajax调用(在js脚本中):

var command = "find";

        if(document.getElementById("text_1").value != "" && document.getElementById("text_2").value != "")
        {
            command += " " + document.getElementById("text_1").value + " " + document.getElementById("text_2").value;
        }   

        var ajax = new XMLHttpRequest;
        ajax.open("POST", "server.php", true);
        ajax.send(command);
        var output_array = ajax.responseText;
        alert(output_array);

出于某种原因,它不会比ajax.open步骤更进一步。在IE10的调试器控制台上,我收到了这个错误:SCRIPT438:对象不支持属性或方法&#39; open&#39;

3 个答案:

答案 0 :(得分:1)

您正在尝试在ClientSide脚本中运行服务器端脚本, 这永远不会奏效。

https://softwareengineering.stackexchange.com/questions/171203/what-are-the-differences-between-server-side-and-client-side-programming

如果你想对text_1和text_2中的数据做一些事情,你应该创建一个php文件,它可以通过AJAX或简单的提交处理发布/获取请求,包含来自这些元素的数据,并使其返回或做任何你希望它最终做的事情。

答案 1 :(得分:0)

你不能使用php(服务器)的javascript变量(客户端)。为此,您必须调用ajax。

<script type="text/javascript">
    rowNum = 0;
    function some_function()
    {    
         var command = "somebasiccommand";
         if(document.getElementById("text_1").value != "" && document.getElementById("text_2").value != "")
         {
            command += " " + document.getElementById("text_1").value + " " + document.getElementById("text_2").value;
         }               
        //AJAX call to a php file on server
       //below is example
       var ajax = window.XMLHttpRequest;
       ajax.open("POST", "yourhost.com/execute.php", true);
       ajax.send(command);   
    }
</script>

这是服务器

上的 execute.php
<?php
        $parameter = $_POST['command']; 

        $output = exec("someExecutable.exe $parameter");

         (...)

?>

答案 2 :(得分:0)

好吧......我几乎改变并测试了很多东西,我发现问题是.send命令的异步属性。我检查responseText的值太快了。将.open的第三个属性设置为false使通信同步,因此我正确地接收了信息。我现在遇到了另一个问题,但它不是一回事,所以我会做另一个帖子。