来自iframe的附加字符串被复制

时间:2012-02-02 01:22:29

标签: javascript jquery html

我正在编写基于iframe的基本上传脚本,但在输出成功消息时遇到问题。上传每个文件后,成功消息只应附加一次,但对于上传的每个文件,附加+1次(1,2,3,次等)。

这是查询文件( uploader.js ):

$(function(){
    $('#uploader .upload_submit').click(function(){
        $('#uploader .upload_iframe').load(function(){
            var JSONResponse = $.parseJSON($(this.contentDocument).text());

            if (JSONResponse.error == true)
            {
                $('#uploader .upload_errors').text('An error occured: '+JSONResponse.error_message)
                    .hide()
                    .slideDown();
            }
            else
            {
                $('#uploader .upload_errors').fadeOut();
                // problem occurs here (should only append once)
                $('#uploader .upload_messages').append('upload success');
            }
        });
    });
});

html 文件:

<!doctype html>
<head>
    <link href="css/style.css" rel="stylesheet" type="text/css" media="screen" />
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script src="uploader.js"></script>
</head>
<body>
<div id="uploader">
    <iframe src="upload.php" name="upload_iframe" class="upload_iframe"></iframe>
    <div class="upload_messages"></div>
    <div class="upload_errors"></div>
    <form action="upload.php" method="post" target="upload_iframe" enctype="multipart/form-data">
        <input type="file" name="userfile" value="" id="userfile" class="upload_field"  />
        <input type="submit" name="upload_submit" value="Submit" class="upload_submit" />
    </form>
</div>
</body>
</html>
upload.php 输出

并示例 JSON (成功时):

{"error":false,"error_message":"","success_data":{"message":"File uploaded successfully","origonal_filename":"egg.jpg"}}

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我通过更改第3行修正了这个问题:

$('#uploader .upload_iframe').load(function(){

到此:

$('#uploader .upload_iframe').one('load', function(){