喵-见缝插针 2015-09-14 10:19 采纳率: 0%
浏览 11

Ajax提交脚本全局

I have this piece of code. this code has to be inside every new loaded ajax page. cause if its outside, it wont work.

example:

<div> Loaded form here , including the script </div>  <- works
<div><div> Loaded form here , </div> script is here </div>  <- do not work

Q: How can i make it able to work without the need to put this script on every of my ajax pages?

code:

  <script>
    $("form").on("submit",function(e) {

        e.preventDefault();


        var btn= $(this).find("input[type=submit]:focus");
        $('<input>').attr({
            type: 'hidden',
            name: btn.attr('name'),
            value: btn.val()
        }).appendTo('form');

        action =  $("form").attr('action');
        $.post(action, $(this).serialize(), function(data) {
            $(".main_center").html(data);

        });
        return false; // prevent normal submit
    });

</script>

if the script is in the loaded file, it will proccess correctly. but if it isnt, it will just refresh the page. cause the loaded file will not find the script that is ment to be used.

  • 写回答

1条回答 默认 最新

  • weixin_33725272 2015-09-14 10:37
    关注

    Is your script in the .main_center div? If so then the returned data will replace it - hence you need to include your script in the data returned in your ajax call.

    Putting the script into a common js file included in your footer works (I've done it myself) so the fault is almost certainly with the structure of your document and the way you are replacing content.

    Will need to see a more of the actual code to properly advise you.

    [Edit] Have you tried

    <div class="main_center">
        <div><form> ....</form></div>
    </div>
    <script>
        $(document).on("submit","form", function(e){ ... });
    </script>
    

    This binds the script to the document and calls it whenever a form is submitted, including forms loaded after the page has been generated

    评论

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用