基本上,我得到了一个 php 文件,我在其中在 header 中创建了一个脚本。
在此脚本中,我使用 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: Object does not support property or method 'open' 。
最佳答案
您正在尝试在客户端脚本中运行服务器端脚本, 那是行不通的。
如果您想对 text_1 和 text_2 中的数据执行某些操作,您应该创建一个 php 文件,该文件可以通过 AJAX 或简单的提交处理 post/get 请求,包含这些元素中的数据,并使其返回或做你想要它最终做的任何事情。
关于javascript - 将字符串从 javascript 发送到 php(在同一文件中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32743642/