1

我正在尝试上传图片而不刷新,但我对 ajax 了解不多。当我使用 ajax 函数提交帖子时,我有 php 文件返回图像 url。

Javascript

 $(document).ready(function() { 

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

        });
    }); 

PHP

  <?php

       $path = "uploads/";

$valid_formats = array("jpg", "png", "gif", "bmp");
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))
                    {
                        $actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
                        $tmp = $_FILES['photoimg']['tmp_name'];
                        if(move_uploaded_file($tmp, $path.$actual_image_name))
                            {


                                $imge1="uploads/".$actual_image_name;
                                echo $imge1;

                            }
                        else
                            echo "failed";
                    }
                    else
                    echo "Image file size max 1 MB";                    
                    }
                    else
                    echo "Invalid file format..";   
            }

        else
            echo "Please select image..!";

        exit;
    }
        ?>

HTML

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

</div>
<img src = "" id="thumb_img" />

现在结果是图片网址。当图像选择 ajax 自动将沙子发布到 php.Php 保存图像并返回 url 并且此 url 显示在目标 div 中。所以现在我需要将此 url 设置为背景 url。像图像选择targetdiv 背景变化。

4

1 回答 1

1

我只会做类似的事情:

$('#myForm').ajaxForm(function(url) { 
   $('#preview').css('background-image', "url(" + url + ")"); 
}); 
于 2013-11-05T09:58:19.053 回答