开发者

jQuery iframe loads multiple times

开发者 https://www.devze.com 2023-03-15 15:25 出处:网络
I am creating a script for file uploading using jQuery and iFrame. So, I have a form with id=\"myform\" and target=\"myframe\" and a frame with id=\"myframe\" and name=\"myframe\" . When the user sele

I am creating a script for file uploading using jQuery and iFrame. So, I have a form with id="myform" and target="myframe" and a frame with id="myframe" and name="myframe" . When the user selects a file the form gets automatically submited and after the iframe loads th results I alert them. The problem is that the first time I upload a file I get one alert, the second two, the third time I upload I get three. My code is like

$("#myform input").change(function () { 
    alert("submitting");
    $("#myform").submit();
});

$("#myform").submit(function () {
    alert(submited);
    $("#myframe").load(function () {
        alert ("loaded!");
        alert ($(this).contents().text());
    });
});

The alerts that I get multiple time is the "loaded!" and the $(this).contents().text() That means the form gets submitted once and the iframe "loads" more than one times. I validated this through the Chrome Console, where m开发者_开发百科y action file gets called only once per submit. Why is this happening?


It appears that you are adding a new handler for $("#myframe").load each time your form is submitted.

try :

$("#myform input").change(function () { 
    alert("submitting");
    $("#myform").submit();
});

$("#myform").submit(function () {
    alert(submited);
    $("#myframe").unbind('load');
    $("#myframe").load(function () {
        alert ("loaded!");
        alert ($(this).contents().text());
    });
});

or:

$("#myform input").change(function () { 
    alert("submitting");
    $("#myform").submit();
});

$("#myframe").load(function () {
    alert ("loaded!");
    alert ($(this).contents().text());
});

$("#myform").submit(function () {
    alert(submited);
});
0

精彩评论

暂无评论...
验证码 换一张
取 消