Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

php - Jquery File Upload Hidden IFrame

I needed a quick explanation on how to get an AJAX style file upload going using a hidden iframe. Here's the portion of the HTML code pertaining to the form:

<div id = "file" class = "info">        
    <form id="file_upload_form" method="post" enctype="multipart/form-data" action='script/uploadScript'>
        <input name="file" id="file" size="27" type="file" /><br />
        <input id = "uploadSubmit" type="submit" name="action" value="Upload" />
        <iframe id="upload_target" name="upload_target" src="" style="width:0;height:0;border:0px solid #fff;"></iframe>
    </form>
</div>

Here's the relevant PHP:

public function uploadScript(){

    $returnVals = array();

    if ($_FILES["file"]["error"] > 0){
        $returnVals['error'] =  "Error: " . $_FILES["file"]["error"] . "<br />";
    }else{
        if ($_FILES["file"]["type"] != "text/plain"){
            $returnVals['error'] = "Badtype";
        }else{
            $returnVals['text'] =  file_get_contents($_FILES["file"]["tmp_name"]);
        }
    }

    echo json_encode($returnVals);
}

So, essentially, the PHP gets the file and checks if it's a text file. Then, I want to access the returned json within javascript. That's where I get confused...

$("#file_upload_form").submit(function() {
    $("#file_upload_form").target = "upload_target";
    $("#upload_target").onload = uploadDone();

});

Ideally, when the upload is complete and the iframe is loaded, this should call

function uploadDone() {
    alert($("#upload_target").contents().find("body").text());  
}

But, that's always blank. Essentially, the returnVals are placed into the iframe body, but after the alert, so the alert has nothing in it. So, is there a way to remedy this little flaw?

Is there any better explanation on how to do this? I've been banging my head against it with different sample codes and etc all day with no luck :/

I essentially want to be able to alert the text returned via the php code. Btw, I'm doing it this way because I want it to be able to work on IE7 and all browsers after.

I'd appreciate any help a ton. Thanks for the time!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Well, I've used something like that:

$("#upload_target")[0].contentWindow.document.body.innerHTML

... instead. But the general approach is similar: check this string, and if it's empty, just do nothing (i.e., return immediately). Otherwise proceed with analyzing this json.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...