自动表单提交不会发送数据

时间:2014-02-23 15:05:52

标签: php jquery forms

这是我用来自动将数据提交到其他文件的一个文件

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<form action="/site/downloadprint" method="post">
<textarea style="" id="file" name="file"></textarea>
<input type="submit" id="submit" />
</form>
<script>

$(document).ready(function(e) {
   var html=$('#download').html(); 
   $('#file').val(html);
   $('#submit').click();
});

</script>


<div id="download">
some html
</div>

它打开www.mysite.com/site/downloadprint但它是空白的。当我手动点击按钮

时,它可以工作
if(isset($_POST["file"]))
{
    $path=$_SERVER['DOCUMENT_ROOT']."/temp/".mt_rand().".html";
    $file=fopen($path, 'w');
    fwrite($file, $_POST['file']);
    fclose($file);

    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($path).'"');
    header('Content-Length: ' . filesize($path));
    readfile($path);

}

EDITED

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<form action="/site/downloadprint" method="post">
<textarea style="display:none;" id="file" name="file"></textarea>
</form>
<script>

$(document).ready(function(e) {
   var html=$('#download').html(); 
   $('#file').val(html).parents("form").submit();
});

    </script>
<div id="download">
some html
</div>

1 个答案:

答案 0 :(得分:0)

您的表单会立即提交。您需要委托提交,直到您将项目写入字段。

最好在submit元素上触发form事件,而不是尝试触发按钮上的click。您可以parent()submit()一起使用来实现:

$(function() {  
    $('#submit').on('click', function(e) {  
        e.preventDefault();
        $('#file').val($('#download').html());
        $(this).parent('form').submit();
    });
});