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


Send a string from javascript to php (in the same file)

基本上,我得到了一个php文件,我在头文件中创建了一个脚本。

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

我尝试了ajax的方式,但由于php和javascript在同一个文件中,它犯了一个错误。

脚本部分如下:

在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);
?>

这是我的ajax调用在我的client.php(在一个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走得更远。开放的步骤。在IE10的调试控制台,我得到了这个错误:SCRIPT438:对象不支持属性或方法'open' .

您正在尝试在ClientSide脚本中运行服务器端脚本,这是行不通的。

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

如果你想做的数据从text_1和text_2,你应该创建一个php文件,可以处理post/get请求通过AJAX或一个简单的提交,从这些元素的特征数据,并使其返回或做任何它是你想要它结束做的

你不能从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 on server
<?php
        $parameter = $_POST['command']; 
        $output = exec("someExecutable.exe $parameter");
         (...)
?>

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