jquery dialog ajax提交表单

在laravel 开发过程中需要用到jquery dialog ajax 数据提交的插件功能这里介绍一下我自己的写法

前端渲染页面HTML

<div id="dialog" title="添加友情链接" style="display: none;overflow:hidden;">
    <form class="form form-horizontal" id="dialogForm" action="store" method="post">
        <input type="hidden" name="_token" value="{{ csrf_token() }}">
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-4"><span class="c-red">*</span>标签名:</label>
            <div class="formControls col-xs-8 col-sm-8">
                <input type="text" class="input-text" autocomplete="off"  placeholder="标签名" style="width: 200px;" name="name">
            </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-4"><span class="c-red">*</span>超链接:</label>
            <div class="formControls col-xs-8 col-sm-8">
                <input type="text" class="input-text" autocomplete="off"  placeholder="超链接" style="width: 200px;" name="href">
            </div>
        </div>
    </form>
</div>
<script type="text/javascript">
$(document).ready(function(){
    $('#dialogK').click(function(){
        $('#dialog').dialog({
            title:"牛逼的大神",
            modal: true,
            autoOpen: false, 
            width: "400",
            bgiframe: false,
            closeOnEscape: true,
            draggable: true,
            resizable:true,
            buttons: {
               "提交": function() {
                   var form = $("#dialogForm");
                   $.ajax({
                        url:form.attr('action'),
                        type:form.attr('method'),
                        data:form.serialize(),
                        dataType:"json",
                        success:function(data){
                            $("#dialog").dialog("close");
                            alert("成功了");
                            window.location.reload();
                        },
                        error:function(){
                            $("#dialog").dialog("close");
                            alert("出错了");
                        }
                   }); 
               },
               "关闭": function() {  
                    $("#dialog").dialog("close");  
                },
            },
        });
        $('#dialog').dialog("open");
    });
});
</script>

控制器代码

//添加友情链接 admin/admin post
public function store(Request $request){
    //验证
    $this->validate(request(),[
      'name'=>'required|min:2',
      'href'=>'required|min:10',
    ]);
    //逻辑
    $data=$request->except("_token");
    $result=\DB::table("links")->insert($data);
    if($result){
        return json_encode($data);
    }else{
        echo 0;
    }
}

这样就OK了 关于路由的编写就省略吧

阅读 102

Comments