【问题标题】:How to pass a php code in a javascript function?如何在 javascript 函数中传递 php 代码?
【发布时间】:2012-04-29 19:18:40
【问题描述】:

我想将上传的文件的名称附加到 ('.list')。文件的名称必须是上传时在服务器中调用的名称。例如,我可以有 2 个文件,但一个称为 mountain.png,另一个称为 mountain2.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>

【问题讨论】:

  • 你必须为此研究 ajax

标签: php javascript jquery ajax


【解决方案1】:

您可以简单地将值 $_FILE 文件名放入 php 变量中,而不是使用回显它

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

并在 append 方法中使用这个 js 变量。 :-)

【讨论】:

  • 只是一个简单的问题,$yourvariable = $_FILES["fileImage"]["name"];进入 php 脚本页面 (imageupload.php) 还是与 javascript 函数位于同一页面?
  • 好吧。如果您使用 2 个不同的页面,您应该通过 Ajax/JSON 在 Javascript 和 PHP 之间交换数据
  • 将文件名作为另一个参数传递,如果存在多个文件,则可以使用数组。 $yourvariable = $_FILES["fileImage"]["name"];这将只存在于您的 imageupload.php 中。谢谢
  • 我已经尝试了你所说的,但问题是它带有一个错误:当我尝试上面的代码时,正则表达式标志无效
  • @RohitKumarChoudhary 我在问题中包含了表单、javascript 和 php 的代码。希望这就是您需要的所有信息:)
【解决方案2】:

您可以选择 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部分,imageupload.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
          }

【讨论】:

    猜你喜欢
    • 2019-07-03
    • 1970-01-01
    • 1970-01-01
    • 2013-02-05
    • 2021-05-13
    • 1970-01-01
    • 2013-01-30
    • 2019-07-30
    • 2017-04-18
    相关资源
    最近更新 更多