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

时间:2012-04-18 11:27:11

标签: php javascript jquery ajax

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

2 个答案:

答案 0 :(得分:0)

您可以简单地将值$ _FILE文件名转换为php变量,而不是使用

回显它
var yourjasvariable=<?php echo $yourvariable?>;

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

答案 1 :(得分:0)

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

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

AJAX js part

<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
          }