如何使用通过函数从Javascript变量分配php变量。值不是从html元素确定的

时间:2015-01-08 01:33:22

标签: javascript php jquery ajax

我不知道如何使用AJAX。我想要获得的变量不是来自html元素,而是来自预定变量。设置两个变量后,此代码将执行一个函数:

// javascript function
function writetofile(file_name, api, wellname){
    <?php
      //something along the lines of this:
      $file_handler = fopen(file_name, "r");
      $api = api;
      $wellname = wellname;
      $result = $api." : ".$wellname;
      fwrite($file_handler, $result);
      $fclose($file_handler);
    ?>   
}

1 个答案:

答案 0 :(得分:0)

包含javascript函数的.php文件中的PHP代码在服务器上运行,永远不会发送到客户端。 javascript代码;函数本身是在没有PHP的客户端(Web浏览器)上运行的。

因为在服务器上没有file_name,api和wellname参数,所以PHP肯定会失败。

// javascript function
function writetofile(file_name, api, wellname) {
  // The stuff here in the php block gets run on the server
  // before anything is ever sent to the web browser.
  // This opens a file (on the server), writes something to it,
  // and closes the file. It produces NO output in the page.
  // The PHP itself is never sent to the browser.
  <?php
    //something along the lines of this:
    $file_handler = fopen(file_name, "r");
    $api = api;
    $wellname = wellname;
    $result = $api." : ".$wellname;
    fwrite($file_handler, $result);
    $fclose($file_handler);
  ?>   
}

这是发送到浏览器的内容:

// javascript function
function writetofile(file_name, api, wellname) {
}

显然,如果你在浏览器中调用该函数,则没有任何反应,因为没有函数体。

如果要使用在客户端浏览器上指定的 file_name api wellname 来运行某些PHP在服务器上,您必须将这些变量发送到服务器,可能需要对POST之类的URL进行AJAX example.com/php_process/dostuff.php请求,其中“dostuff.php”将读取POST变量(如任何形式)并与他们做点什么。然后它应该回应结果,或者至少是状态指示器。

如何从Javascript进行AJAX POST是另一个问题,它已经在SO上有很多答案。