AJAX Post有时会起作用,有时它不会,为什么?

时间:2017-09-18 14:55:40

标签: javascript php jquery ajax laravel

我的网页上有几个ajax帖子,我发现有一天他们可以正常工作:

  • 在控制器中执行该方法。
  • 不刷新页面。

有时它不会:

  • 在控制器中执行该方法。
  • 转到空白页。

我没有找到他们何时工作或他们不相关的关系,这似乎是随机的,但我希望不是。 我搜索了几个堆栈溢出的帖子和文章,仍然无法找到原因,因此我为什么要做这个任务。希望你能理解。

有时可以运行的Ajax调用示例,有时不会:

$(document).ready(function() {

        $('form.ajaxaccount').on('submit', function(event) {
            event.preventDefault();

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            $.ajax({
                method: 'POST',
                url: '/saveaccount', // This is the url we gave in the route
                data: $('form.ajaxaccount').serialize(),
                success: function(response){ // What to do if we succeed
                    var stack_bar_bottom = {"dir1": "up", "dir2": "right", "spacing1": 0, "spacing2": 0};
                    new PNotify ({
                        title: "Sucesso",
                        text: "Editado com sucesso! ",
                        styling: "bootstrap3",
                        addclass: "stack-bottomright custom",
                        nonblock: {
                            nonblock: true
                        },
                        stack: stack_bar_bottom
                    });  
                },
                error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
                    var stack_bar_bottom = {"dir1": "up", "dir2": "right", "spacing1": 0, "spacing2": 0};
                    new PNotify ({
                        title: "Erro :(",
                        text: "Os dados inseridos não foram guardados. Tenta novamente",
                        styling: "bootstrap3",
                        addclass: "stack-bottomright custom",
                        nonblock: {
                            nonblock: true
                        },
                        stack: stack_bar_bottom
                    });  
                }
            });
        });
    });

完整页面:

    <!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Wolistic</title>
    <link href="./css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <link href="./css/style.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700" rel="stylesheet">
    <script src="https://use.fontawesome.com/a3f24bf03b.js"></script>
    <link href="dist/notyf.min.css" rel="stylesheet">
    <script src="dist/notyf.min.js"></script>
    <link rel="stylesheet" href="{{ asset('vendor/backpack/pnotify/pnotify.custom.min.css') }}">
</head>

<body>
    @include('frontoffice.login_popup')
    @include('frontoffice.register_popup')
    <header>
        <div class="top_bar_right">
            <div class="container">
                <ul>
                @if (Auth::guard('web_customer')->guest())
                        <!--Seller Login and registration Links -->
                        <li><a id="openloginpopup"> Iniciar Sessão </a></li>
                        <li><a id="openregisterpopup"> Registar </a></li>

                    <ul class="lang_switch">
                        <li>Pt</li>
                        <li><img src="./img/down_arrow.png" width="9"></li>
                    </ul>
                @else
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
                            {{ Auth::guard('web_customer')->user()->name }} <span class="caret"></span>
                        </a>

                        <ul class="dropdown-menu" role="menu">
                            <li>
                                <a href="{{ url('/customer_logout') }}"
                                    onclick="event.preventDefault();
                                            document.getElementById('logout-form').submit();">
                                    Logout
                                </a>

                                <form id="logout-form" action="{{ url('/customer_logout') }}" method="POST" style="display: none;">
                                    {{ csrf_field() }}
                                </form>
                            </li>
                        </ul>
                    </li>
                @endif
                </ul>
            </div>
        </div>
        <nav id="mainNav" class="navbar navbar-default">
            <div class="container">

                <div class="navbar-header">
                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse-1">
                    <span class="sr-only">Toggle navigation</span> Menu <i class="fa fa-bars"></i>
                </button>
                    <a class="navbar-brand page-scroll" href="{{ url('/eventos') }}">
                        <img src="img/wolistic_logo.png" class="logo" alt="Wolistic" title="Wolistic" />
                    </a>
                </div>

                <div class="collapse navbar-collapse" id="navbar-collapse-1" class="menu">
                    <ul class="nav navbar-nav navbar-right">
                        <li>
                            <a class="page-scroll" href="#download">Sobre Nós</a>
                        </li>
                        <li>
                            <a class="page-scroll" href="#features">Workshops</a>
                        </li>
                        <li>
                            <a class="page-scroll" href="#contact">Eventos</a>
                        </li>
                        <li>
                            <a class="page-scroll" href="#contact">Voluntariado</a>
                        </li>
                        <li>
                            <a class="page-scroll" href="#contact">Submeter Evento</a>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>
        <form class="col-md-12 search_form">
            <div class="container">
                <input type="text" name="search_term" class="search_term" id="search_term" placeholder="O que procuras? (Ex. Permacultura)" />
                <select name="event_type" id="event_type" class="event_type" placeholder="Tipo">
                    <option value="" disabled selected hidden>Tipo</option>
                    <option>Evento</option>
                    <option>Workshop</option>
                    <option>Voluntariado</option>
                </select>
                <select name="event_local" id="event_local" class="event_local" placeholder="Tipo">
                    <option value="" disabled selected hidden>Local</option>
                    <option>Porto</option>
                    <option>Braga</option>
                    <option>Lisboa</option>
                </select>
                <input type="text" name="event_begin_date" class="event_begin_date" id="event_begin_date" placeholder="Data (início)" />
                <input type="text" name="event_end_date" class="event_end_date" id="event_end_date" placeholder="Data (fim)" />
                <button id="submit" class="search_submit"></button>
            </div>
        </form>
    </header>
    <main>
        <div class="container">
            <div class="breadcrumb">
                <span>Início</span> > <span>Perfil</span>
            </div>
            <div class="profile_title">
                A MINHA CONTA
            </div>

            <div class="row">
                <div class="left_sidebar col-md-3 left_aboutus">
                    <img 
                        @if (is_null($customer->profile_pic)) 
                            src="\uploads\{{ $customer->profile_pic }}"
                        @else
                            src="./img/default_profile_picture.png"
                        @endif
                        class="img-responsive profile_pic" />
                    <h1 class="profile_name"> {{ $customer->name }} </h1>

                    <div class="perfil-menu text-left">
                        <div class="perfil-accordion">
                            <div class="panel-group" id="accordion">
                                <div class="panel panel-default notbordered">
                                    <div class="panel-heading active">
                                        <h4 class="panel-title" >
                                            <a class="accordion-perfil-tog-link-main" href="{{ url('/account') }}">Eu sou</a>
                                        </h4>
                                    </div>
                                </div>
                                <div class="panel panel-default notbordered">
                                    <div class="panel-heading">
                                        <h4 class="panel-title">
                                            <a data-toggle="collapse" data-parent="#accordion" href="#1collapse2" aria-expanded="false" class="collapsed">Eu gosto<span class="accordion-perfil-tog-link accordion-perfil-tog-plus"><i class="fa fa-angle-down" aria-hidden="true"></i></span></a>
                                        </h4>
                                    </div>
                                    <div id="1collapse2" class="panel-collapse collapse" aria-expanded="false" style="height: 0px;">
                                        <div class="panel-body">
                                            <ul>
                                                <li><a href="{{ url('/customerinteresses') }}" class="">Os meu interesses</a></li>
                                                <li><a href="{{ url('/wishlist') }}" class="">Wishlist</a></li>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                                <div class="panel panel-default">
                                    <div class="panel-heading ">
                                        <h4 class="panel-title">
                                            <a data-toggle="collapse" data-parent="#accordion" href="#1collapse3" class="collapsed" aria-expanded="false">Eu quero<span class="accordion-perfil-tog-link accordion-perfil-tog-plus"><i class="fa fa-angle-down" aria-hidden="true"></i></span></a>
                                        </h4>
                                    </div>
                                    <div id="1collapse3" class="panel-collapse collapse" aria-expanded="false" style="height: 0px;">
                                        <div class="panel-body">
                                            <ul>
                                                <li><a href="{{ url('/newsletter') }}" class="">Newsletter</a></li>
                                                <li><a href="{{ url('/password_reset') }}" class="">Alterar password</a></li>
                                                <li><a href="{{ url('/accountdelete') }}" class="">Apagar conta</a></li>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!--
                    <div class="button_anunciante">EU SOU ANUNCIANTE</div>
                    -->

                    <div class="perfil-menu-anunciante text-left">
                        <div class="perfil-accordion">
                            <div class="panel-group" id="accordion">
                                <div class="panel panel-default ">
                                    <div class="panel-heading ">
                                        <h4 class="panel-title">
                                            <a class="accordion-perfil-tog-link-main" href="{{ url('/advertiser') }}">Eu sou anunciante</a>
                                        </h4>
                                    </div>
                                </div>
                                <div id="anunciante-options" class="">
                                    <div class="panel panel-default ">
                                        <div class="panel-heading ">
                                            <h4 class="panel-title">
                                                <a data-toggle="collapse" data-parent="#accordion" href="#2collapse2" aria-expanded="false" class="collapsed">Os meus eventos<span class="accordion-perfil-tog-link accordion-perfil-tog-plus"><i class="fa fa-angle-down" aria-hidden="true"></i></span></a>
                                            </h4>
                                        </div>
                                        <div id="2collapse2" class="panel-collapse collapse" aria-expanded="false" style="height: 0px;">
                                            <div class="panel-body">
                                                <ul>
                                                    <li><a href="{{ url('/myevents') }}" class=""> Os meus eventos </a></li>
                                                    <li><a href="{{ url('/addnewevent') }}" class=""> Submeter evento </a></li>
                                                </ul>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="page_content col-md-6 col-md-offset-1">

                    <div class="separator"></div>

                    <h3 class="personal_data">DADOS PESSOAIS</h3>
                    <div class="separator_personal"></div>
                    {{ Form::open(array('method'=>'post','class'=> 'profile_form ajaxaccount', 'url'=>'/saveaccount')) }}
                            <div class="form-group">
                                <label for="exampleInputEmail1"> Nome </label>
                                <input type="text" name="name" class="form-control" value="{{ $customer->name }}" placeholder="{{ $customer->name }} ">
                            </div>
                            <div class="form-group">
                                <label for="exampleInputEmail1"> Email </label>
                                <input type="email" name="email" class="form-control" value="{{ $customer->email }}" placeholder="{{ $customer->email }}"> 
                            </div>
                            <div class="form-group">
                                <label for="exampleInputEmail1"> Telemóvel </label>
                                <input type="text" name="phone" class="form-control" data-country="PT" value="{{ $customer->phone }}" placeholder="{{ $customer->phone }} ">
                            </div>
                            <div class="form-group">
                                <label for="exampleSelect1">Distrito / região </label>
                                <select class="form-control" name="districtID" id="exampleSelect1">
                                        @foreach ($districts as $district)
                                            <option value="{{ $district->id }}" > {{ $district->name }} </option>
                                        @endforeach
                                        </select>
                            </div>
                            <button type="submit" class="btn btn-primary">GUARDAR DADOS</button>
                    {{Form::close()}}
            </div>
        </div>
        </div>
        <div class="separator"></div>
        <div class="separator"></div>
        <div class="separator"></div>
        <div class="separator"></div>
    </main>

    @include('frontoffice.footer')

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js "></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js "></script>
    <script src="./js/bootstrap.min.js "></script>
    <script src="./js/script.js "></script>
    <script src="vendor/backpack/pnotify/pnotify.custom.min.js"></script>
    <script>
        $(document).ready(function() {

            $('form.ajaxaccount').on('submit', function(event) {
                event.preventDefault();

                $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                });

                $.ajax({
                    method: 'POST',
                    url: '/saveaccount', // This is the url we gave in the route
                    data: $('form.ajaxaccount').serialize(),
                    success: function(response){ // What to do if we succeed
                        var stack_bar_bottom = {"dir1": "up", "dir2": "right", "spacing1": 0, "spacing2": 0};
                        new PNotify ({
                            title: "Sucesso",
                            text: "Editado com sucesso! ",
                            styling: "bootstrap3",
                            addclass: "stack-bottomright custom",
                            nonblock: {
                                nonblock: true
                            },
                            stack: stack_bar_bottom
                        });  
                    },
                    error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
                        var stack_bar_bottom = {"dir1": "up", "dir2": "right", "spacing1": 0, "spacing2": 0};
                        new PNotify ({
                            title: "Erro :(",
                            text: "Os dados inseridos não foram guardados. Tenta novamente",
                            styling: "bootstrap3",
                            addclass: "stack-bottomright custom",
                            nonblock: {
                                nonblock: true
                            },
                            stack: stack_bar_bottom
                        });  
                    }
                });
            });
        });
    </script>
</body>
</html>

上页的表格

{{ Form::open(array('method'=>'post','class'=> 'profile_form ajaxaccount', 'url'=>'/saveaccount')) }}
                        <div class="form-group">
                            <label for="exampleInputEmail1"> Nome </label>
                            <input type="text" name="name" class="form-control" value="{{ $customer->name }}" placeholder="{{ $customer->name }} ">
                        </div>
                        <div class="form-group">
                            <label for="exampleInputEmail1"> Email </label>
                            <input type="email" name="email" class="form-control" value="{{ $customer->email }}" placeholder="{{ $customer->email }}"> 
                        </div>
                        <div class="form-group">
                            <label for="exampleInputEmail1"> Telemóvel </label>
                            <input type="text" name="phone" class="form-control" data-country="PT" value="{{ $customer->phone }}" placeholder="{{ $customer->phone }} ">
                        </div>
                        <div class="form-group">
                            <label for="exampleSelect1">Distrito / região </label>
                            <select class="form-control" name="districtID" id="exampleSelect1">
                                    @foreach ($districts as $district)
                                        <option value="{{ $district->id }}" > {{ $district->name }} </option>
                                    @endforeach
                                    </select>
                        </div>
                        <button type="submit" class="btn btn-primary">GUARDAR DADOS</button>
                {{Form::close()}}

可能出现什么问题?

0 个答案:

没有答案