如何在javascript函数中传递php代码

How to pass a php code in a javascript function?

本文关键字:php 代码 函数 javascript      更新时间:2023-09-26

我想将上传到('.list')的文件的名称附加到('.list')。文件的名称必须是上传时在服务器中调用的名称。例如,我可以有 2 个文件,但一个被称为山.png另一个被称为山2.png。

但问题是我如何将 $_FILES["fileImage"]["name"] 作为参数传递给我的 js 函数,然后附加它,因为 javascript 函数和 php 脚本位于不同的页面上(即使 php 脚本确实回调了 javascript 函数)?

更新

下面是javascript代码:

以下是表单代码(QandATable.php)

<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='startImageUpload(this);' class='imageuploadform' >
        <p>Image File: <input name='fileImage' type='file' class='fileImage' />
        <input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' />
        </p> 
        <ul class='list'></ul>
        </form>

下面是javascript函数(QandATable.php)

      function stopImageUpload(success){
  var nameimagefile = <?php echo $nameimagefile?>;
      var result = '';
      if (success == 1){
         result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
         $('.listImage').append(nameimagefile + '<br/>');
      }
      else {
         result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
      }
     return true;
    }

下面是 php 脚本(imageupload.php):

   $result = 0;
    $nameimagefile = '';
        if( file_exists("ImageFiles/".$_FILES['fileImage']['name'])) {
            $parts = explode(".",$_FILES['fileImage']['name']);
            $ext = array_pop($parts);
            $base = implode(".",$parts);
            $n = 2;
            while( file_exists("ImageFiles/".$base."_".$n.".".$ext)) $n++;
            $_FILES['fileImage']['name'] = $base."_".$n.".".$ext;
            move_uploaded_file($_FILES["fileImage"]["tmp_name"],
            "ImageFiles/" . $_FILES["fileImage"]["name"]);
            $result = 1;
$nameimagefile = $_FILES["fileImage"]["name"];
        }
            else
              {
              move_uploaded_file($_FILES["fileImage"]["tmp_name"],
              "ImageFiles/" . $_FILES["fileImage"]["name"]);
              $result = 1;
$nameimagefile = $_FILES["fileImage"]["name"];
              }

        ?>
        <script language="javascript" type="text/javascript">window.top.window.stopImageUpload(<?php echo $result;?>);</script>

您可以简单地将值 $_FILE 文件名放入 php 变量中,然后使用

var yourjasvariable=<?php echo $yourvariable?>;

并在追加方法中使用此 js 变量。

你可以选择 AJAX 来做你想做的事。以 JSON 格式写入数据。 JSON可以从PHP和JavaScript读取- 读取 JSON 以在 PHP 中获取数据- 读取 AJAX 结果(JSON)以从 PHP 获取数据

我会做这样的事情(未经测试的示例)

AJAX js 部分

<form method='post' enctype='multipart/form-data' onsubmit='startAjaxImageUpload(this);' >
      ...
</form>  
/*
 * ajax functions 
 */
function startAjaxImageUpload(event){
    /* Collect your formdatas as json with jquery this datas will be sent to php*/
    var formDatas = {
            'value1'        : $('input[test1=eid]').val(),
            'value2'        : $('input[id=test2_id]').val(),
            ......
        'value3'    : $('input[id=test3_id]').val()
        };
    $.ajax({
        cache: false,
        url:  "imageupload",
        data: formDatas,
        success: function(data) {
            // data is the json Result from php => imageupload.php do what u want with them in js
            // use the next line if u wanna see which json datas comes back from php if the ajax call wass successfull
            // console.log("data is %o, data);
            // ....
        }
        error:function(data){
            // error function
            // data is the json Result from php => imageupload.php do what u want with them in js
            // use the next line if u wanna see which json datas comes back from php if the ajax call wass successfull
            // console.log("data is %o, data);
            alert(damn, something went wrong);
        }
    })
}

PHP部分,图片上传.php

    $result = 0;
    $nameimagefile = '';
    .....
    // if done ure work on server side and no error was found, pass the  result back to starAjaxImageUpload success function
    return $nameimagefile = $_FILES["fileImage"]["name"];
    }else
    // abbort ajax, ajax error function will used
    return false
          }