Ajax、JQuery&;PHP-将PHP变量传递给JQuery


Ajax, JQuery & PHP - Passing PHP variable to JQuery

我有一个页面,允许用户上传多个文件并预览它们,而无需使用jquery刷新页面。在php中,我为每个文件名生成一个唯一的file_id,然后我想将其传递回JQuery,并使用它加载预览图像等。

我希望我已经把自己解释清楚了。

谢谢你的指点!

PHP代码:

   // php code to upload file and generate unique file id. then...
   if (move_uploaded_file($main_image, $file)) { 
      echo "success"; 
      echo $file_id; // <--- I WANT TO PASS THIS VARIABLE BACK IN TO JQUERY
    } else {
        echo "error";
    }

J查询代码:

$(function(){
        var btnUpload=$('#upload_main');
        var mestatus=$('#mestatus');
        var button=$('#button');
        var files=$('#main_file');
        new AjaxUpload(btnUpload, {
            action: 'classified-ads/upload-classified-image.php?filenumber=1',
            name: 'file1',
            onSubmit: function(file, ext){
                 if (! (ext && /^(jpg|png|jpeg|gif|'')$/.test(ext))){ 
                    // extension is not allowed 
                    mestatus.text('Only JPG, PNG or GIF files are allowed');
                    return false;
                }
                mestatus.html('<img src="extras/ajaxuploader/progress_bar.gif" height="30" width="340">');
                button.html('Loading...');
                $('#upload_main').removeClass('hover').addClass('upload_button_loading');
            },
            onComplete: function(file, response){
                //On completion clear the status
                mestatus.text('Photo Uploaded Sucessfully!');
                button.html('Change Photo');
                $('#upload_main').removeClass('upload_button_loading').addClass('upload_button');
                //On completion clear the status
                files.html('');
                //Add uploaded file to list
                if(response==="success"){
                var file2 = file.replace(/'s/g, "_");
                            var file_id= file_id;
                        $('<div></div>').appendTo('#main_file').css('background-image', "url(/ht/classified-ads/temp_images/prev1_<?php echo $parsed_user;?>_"+file_id+")").addClass('main_success');
                        $("#image1_temp").val("main1_<?php echo $parsed_user;?>_"+file_id+"");
                        $("#thumbnail_temp").val("thumbnail_<?php echo $parsed_user;?>_"+file_id+""); 
                    } else{
                        $('<li></li>').appendTo('#main_file').text(file).addClass('error'); 
                    }
                }
            });
        });

在您的PHP中:

$response = array('result' => 'success', 'file_id' => $file_id);
echo json_encode($response);

在您的jQuery中:

var obj = $.parseJSON(response);

然后,您将使用if (obj.result == 'success')检查响应是否成功,并使用obj.file_id 获取file_id

最简单的方法是允许返回多个值:

// Make a variable to hold data to send back and keep track of your separator
$data = '';
$separator = 1;
// Put this in a loop, your loop will depend on how many file uploads you have
// I did not do the loop for you
if (move_uploaded_file($main_image, $file)) { 
  // echo "success"; Take this out
  if ($separater==1){
      $data .= $file_id;
  } else {
      $data .= ','.$file_id;
  }
  $separater++;
}
// Now outside the loop echo the results back
echo $data;

有了这些信息的回显,您可以使用Javascript(Jquery)对其进行操作。只需使用split(',');它为您提供了一个所需的文件名数组。


如果你只想返回一个值,这意味着你只有一个文件id可以发送回关于循环的所有内容,PHP将是这样的:

if (move_uploaded_file($main_image, $file)) { 
// echo "success"; Take this out
$data = $file_id;
// Now echo the results back
// Its been a while since I've done this but there may be times its ok to use return
echo $data;
} else {
// Handel error here
echo "error";
}

现在,根据您的代码,应该在这里提取并处理这些回声信息:

onComplete: function(file, response){ ... }

你不需要寻找"成功",而是需要更改代码来寻找文件id或类似错误的东西(这更容易),比如:

if(response!=="error"){
// Now you can use your variable "response" here since it contains the file id
} else { 
// Handle the error
}

我之所以给你一个关于恢复多个值的详细解释,是因为随着你开始制作更高级的表单,这种情况更常见,现在使用也不会有什么坏处。例如,通过这种方式可以允许多个文件上传。例如,当我使用AJAX时,我所做的是回显类似这样的东西:

1::value,value,value

现在,我只需要先通过:将其拆分为数组,然后通过,例如,这一行显示No Error Happened(1,我们知道它也是TRUE),这是您的数据:value,value,value。您现在可以在Jquery中使用这些值,也可以打印到文档中。

您应该在JqueryAJAX页面上查看深入的示例和解释,它解释了您在返回结果时遇到的麻烦。看看。完成。成功。尤其是完成。