duanshan1511
duanshan1511
2013-07-13 13:09
浏览 148

jQuery $ .get请求无效

I have a file upload form, the following javascript fires as soon as the form is submitted:

$("#uploader").submit(function() {
    $("#indicator").show();
    alert("Submitted");
    var refresh = setInterval(function() {
        $.get("progress.php?getprogress&randval=" + Math.random(), function(data) {
            alert("Got " + data);
            $("#indicator .bar div").width(data + "%");
            if (data == 100) {
                clearTimeout(refresh);
                $("#indicator").addClass("done");
            }
        });
    }, 250);
});

I added some alerts to debug, I get the alert("Submitted"), but not the one alerting the data. The php is fine, opening it in a separate window gives the correct values, but the javascript does not get it. Another weird thing is that if I stop the page load, the alert() with the value fires and code is processed.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongwei4444
    dongwei4444 2013-07-13 13:24
    已采纳

    Ok solved this by using an <iframe>:

    <form action="save.php" method="post" target="theiframe">...</form>
    <iframe name="theiframe" src="about:blank"></iframe>
    

    Still using javascript, but no e.preventDefault();

    点赞 评论
  • douyi4205
    douyi4205 2013-07-13 13:11

    You are not cancelling the form submission, that means your page will refresh. To cancel the submission you can call event.preventDefault()

    $("#uploader").submit(function(e) {
        e.preventDefault();
    

    Just moving comments into the answer since your question actually has more to it than what you wrote above.

    It is impossible to do two actions on the submit and expect them both to happen. Especially when one is trying to run code as the age is submitting. There are JavaScript libraries that do file uploads, you might want to look into them. BUT the basic idea is submitting the form to a hidden iframe on the page.

    <form action="YourSubmitPage.php" method="POST" target="hiddenIframe">
        ...fileds here...
    </form>
    <iframe id="hiddenIframe" name="hiddenIframe" style="display:none" />
    
    点赞 评论
  • douxiaomang5640
    douxiaomang5640 2013-07-13 13:13

    I hope your function is inside a $(document).ready() statement

    点赞 评论

相关推荐