0

我使用脚本输出上传的图像预览。它工作正常。我只想在一个 div 中显示图像,在另一个 div 中显示错误或成功消息。有没有机会这样做?这是代码。

Java 脚本

<script type="text/javascript">
    $(document).ready(function(){
       $('#photoimg').live('change', function(){
          $("#preview").html('');
          $("#preview").html('<img src="loader.gif" alt="Uploading...."/>');
          $("#imageform").ajaxForm(
          {
             target: '#preview'
          }).submit();
       });
    });
</script>

HTML 代码

<?php
    include('db.php');
    session_start();
    $session_id='1'; // User login session value
?>

<div id="output"></div>

<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
Upload image <input type="file" name="photoimg" id="photoimg" />
</form>

<div id='preview'>
</div>

PHP 代码

include('db.php');
session_start();
$session_id='1'; // User session id
$path = "uploads/";

$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
    $name = $_FILES['photoimg']['name'];
    $size = $_FILES['photoimg']['size'];
    if(strlen($name))
    {
        list($txt, $ext) = explode(".", $name);
        if(in_array($ext,$valid_formats))
        {
            if($size<(1024*1024)) // Image size max 1 MB
            {
                $actual_image_name = time().$session_id.".".$ext;
                $tmp = $_FILES['photoimg']['tmp_name'];
                if(move_uploaded_file($tmp, $path.$actual_image_name))
                {
                    mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
                    echo "<img src='uploads/".$actual_image_name."' class='preview'>";

                    echo "<span class=ok-msg">Image has been uploaded..!</span>";
                }
                else
                    echo "<span class=error-msg">failed<span>";
            }
            else
                echo "<span class=error-msg">Image file size max 1 MB</span>";
        }
        else
            echo "<span class=error-msg">Invalid file format..</span>";
    }
    else
        echo "<span class=error-msg">Please select image..!</span>";
    exit;
}

我喜欢显示所有的消息(error-msg、ok-msg)并在 div 输出和图像中的同一位置 div 预览。谁能告诉我该怎么做。提前致谢。

4

2 回答 2

1

使用json dataTypesuccess callback function喜欢,

$("#imageform").ajaxForm(
{
    dataType:'json',
    success:function(json){
       $('#output').html(json.img);
       $('#preview').html(json.msg);
    }
}).submit();

PHP中

返回数据

echo json_encode(array('img'=>"<img src='...' />",'msg'=>"Message goes here"));
return;
于 2013-07-03T08:01:45.527 回答
0

你可以使用-success : 和 error : eventListner

$("#imageform").ajaxForm(
{
dataType:'json',
success:function(json){
   write the success msg 
}
error: function() { 
    write the error msg 
}   


}).submit();
于 2013-07-03T08:13:12.090 回答