将变量从 ajax 传递到 php 失败


Passing variable from ajax to php fails

我对javascript和ajax很陌生,我想做一些工作:

我有一个页面,您可以在其中选择要上传文件的人员的姓名。然后,通过javascript,您可以在变量中获取该名称,并通过ajax将变量传递给进行上传的.php文件。问题是没有传递任何名称,并且文件上传到所有人员姓名所在的同一文件夹中,而不是在其中一个文件夹中。这是我目前得到的代码:

代码中的一些新编辑

.html

<select id="cuadro" name="op-cliente">
         <option>bbraun</option>
         <option>biosystems</option>
         <option>seat</option>
         <option>tradsp</option>
         <option>tradin</option>
         <option>vanderlande</option>
   </select>
   <script type="text/javascript">
              $(function() {
              // Setup html5 version
              $("#uploader").pluploadQueue({
                // General settings
                runtimes : 'html5,flash,silverlight,html4',
                url : 'plupload/examples/upload.php',
                multipart_params: {'valor' : $('#cuadro').val()},
                chunk_size: '5mb',
                rename : true,
                dragdrop: true,    
                filters : {
                // Maximum file size
                max_file_size : '500mb',
                // Specify what files to browse for
                mime_types: [
                ]
                },
                flash_swf_url : 'plupload/js/Moxie.swf',
                silverlight_xap_url : 'plupload/js/Moxie.xap'
                });
              });
            </script>

.php

   $valor = $_REQUEST['valor'];
$targetDir = ".." . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . "uploads" . DIRECTORY_SEPARATOR . $valor;
$cleanupTargetDir = true; // Remove old files
$maxFileAge = 7 * 24 * 3600; // Temp file age in seconds

// Create target dir
if (!file_exists($targetDir)) {
    @mkdir($targetDir);
}
// Get a file name
if (isset($_REQUEST["name"])) {
    $fileName = $_REQUEST["name"];
} elseif (!empty($_FILES)) {
    $fileName = $_FILES["file"]["name"];
} else {
    $fileName = uniqid("file_");
}
$filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
// Chunking might be enabled
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;

// Remove old temp files    
if ($cleanupTargetDir) {
    if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
        die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
    }
    while (($file = readdir($dir)) !== false) {
        $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
        // If temp file is current file proceed to the next
        if ($tmpfilePath == "{$filePath}.part") {
            continue;
        }
        // Remove temp file if it is older than the max age and is not the current file
        if (preg_match('/'.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) {
            @unlink($tmpfilePath);
        }
    }
    closedir($dir);
} 

而最后一次我得到了一些可以揭示的东西:如果我改变这个:multipart_params: {'valor' : $('#cuadro').val()},到这个:multipart_params: {'valor' : '5'},它工作并创建一个名为"5"的文件夹......

非常感谢您的时间

我看到您将其作为 GET 值传递。因此,该变量不在开机自检中。

改变 $_POST['valor']; $_GET['valor'];

另一种选择

<select id="cuadro" name="op-cliente">
     <option>bbraun</option>
     <option>biosystems</option>
     <option>seat</option>
     <option>tradsp</option>
     <option>tradin</option>
     <option>vanderlande</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
$('#cuadro').change(function(){
    var selectedValue = $("#cuadro").val();
    $.ajax({url:"plupload/examples/upload.php?valor="+selectedValue,cache:false,success:function(result){
        alert("success");
    }});
});
</script>

上传.php(为此,请使用$_GET获取valor

$targetDir = ".." . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . 
                "uploads" . DIRECTORY_SEPARATOR . $_GET['valor'];
我认为

您面临的问题是因为您在一个请求中发送了该人的姓名,在另一个请求中发送了文件,但是如果您在同一请求中发送它们,您将获得所需的结果我已经对此进行了测试,它对我有用。

这是索引.php

<html>
<head>
<script type="text/javascript" src="jquery-1.12.0.js"></script>
<script type="text/javascript">
$(function(){
    $('#my_Form').on('submit',function(e){
        e.preventDefault();
        var $form=$(this);
        var fd = (window.FormData)? new FormData($form[0]) : null;
        var data=(fd !==null)? fd : $form.serialize(); 
        $.ajax($form.attr('action'),{
            type:$form.attr('method'),
            contentType:false,
            processData:false,
            dataType:'json',
            data:data,
            success:function(response){alert("sucess");},
            error:function(response){alert("update failre");}
        });
    });
});
</script>
</head>
<body>
<form id="my_Form" action="upload.php" method="POST" enctype="multipart/form-data">
<fieldset>
<select name="person" >
<option value="jhon">jhnon</option>
<option value="albert">albert</option>
<option value="achabahe">achabahe</option>
<option value="Tom">Tom</option>
</select>
<input type="file" name="myFile"/>
<input type="submit" value="Upload"/>
</fieldset>
</form>
</body>
</html>

这是上传.php

<?php
$tempFile=$_FILES['myFile']['tmp_name']; 
$targetDir = ".." . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . "uploads" . DIRECTORY_SEPARATOR . $_POST['person'];
$uploadedFileName= $_FILES['myFile']['name'];
$maxFileAge=7*24*3600;
$cleanUpTargetDir=true;
if(!file_exists($targetDir)){
    @mkdir($targetDir); 
}
if($dir=opendir($targetDir)){
while($file=readdir($dir)) {
    $file=$targetDir.DIRECTORY_SEPARATOR.$file;
    if(filemtime($file)<(time() - $maxFileAge  )){
        @unlink($file);
    }   
}   
}else{
  die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');    
}
$filePath= $targetDir . DIRECTORY_SEPARATOR .$uploadedFileName;
move_uploaded_file($tempFile,$filePath);
?>