Laravel 5.8纯Javascript提取AJAX PromiseStatus返回被拒绝

时间:2019-06-20 08:58:31

标签: javascript json ajax laravel-5.8

当前,我在获取现有客户的AJAX响应方面遇到问题。当我在不同的浏览器中使用相同的帐户访问仪表板时,例如:http://www.inwrite.com/turtle/dashboard

1http://www.inwrite.com/turtle/dashboard使用Google Chrome浏览器,响应返回的承诺状态为“已解决”。在此处查看所附图片:

promise status resolved

但是,在其他浏览器上,甚至在Chrome Incognito上,它都将Promise状态返回为“已拒绝”。

promise status rejected

除此之外,我尝试使用其他帐户登录,但返回了相同的错误。此类“在不同的浏览器/选项卡中呈现AJAX调用”的可能原因是什么?

dashboard_left.blade.php

<div class="dashboard-box">
    <div class="forehead">
        <div class="box-profile-pic" style="background: url(https://www.fiaregion1.com/wp-content/uploads/2018/06/gdpr_profile-picture-400x400.jpg) no-repeat;">
        </div>
    </div>
    <div class="dashboard-contents">
        <h3 class="profile-name">{{ $user->first_name }} {{ $user->last_name }}</h3>
        <div class="btns">
            <button class="btn btn-blue btn-edit" data-toggle="modal" data-target="#modalBox" id="btn-update-profile"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> Edit</button>
            <a class="btn btn-red" href="{{ url('/logout') }}"><i class="fa fa-sign-out" aria-hidden="true"></i> Log Out</a>
        </div>
        <ul class="order-type-list">
            <a class="list-link" href="#">
                <li class="row">
                    All Orders
                </li>
            </a>
            <a class="list-link" href="#">
                <li class="row">
                    New Orders
                </li>
            </a>
            <a class="list-link" href="#">
                <li class="row">
                    Orders Fulfilled
                </li>
            </a>
            <a class="list-link" href="#">
                <li class="row">
                    Orders Processing
                </li>
            </a>
            <a class="list-link" href="#">
                <li class="row">
                    Orders Cancelled
                </li>
            </a>
        </ul>
    </div>
</div>

<!-- Modal: modalCart -->
<div class="modal fade modal-edit-profile" id="modalBox" data-backdrop="static" data-keyboard="false" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
  aria-hidden="true">
  <input type="hidden" class="js-input-id" value="" />
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <!--Header-->
      <div class="modal-header">
        <h4 class="modal-title" id="myModalLabel">Update Profile</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <!--Body-->
      <div class="modal-body">
          <div class="form-group">
            <label class="lbl-input" for="first_name">First Name:</label>
            <input type="text" class="form-control txt-input single-field" id="first_name" name="first_name" required>
          </div>
          <div class="form-group">
            <label class="lbl-input" for="last_name">Last Name:</label>
            <input type="text" class="form-control txt-input single-field" id="last_name" name="last_name" required>
          </div>
          <div class="form-group">
            <label class="lbl-input" for="email">Email:</label>
            <input type="text" class="form-control txt-input single-field" id="email" name="email" disabled>
          </div>
          <div class="form-group">
            <label class="lbl-input" for="password">New Password(leave blank if unchanged):</label>
            <input type="password" class="form-control txt-input single-field" id="password" name="password">
          </div>
          <div class="form-group">
            <label class="lbl-input" for="password2">Confirm New Password:</label>
            <input type="password" class="form-control txt-input single-field" id="password2" name="password2">
          </div>
          <div class="form-group">
            <label class="lbl-input" for="occupation">Occupation:</label>
            <input type="text" class="form-control txt-input single-field" id="occupation" name="occupation">
          </div>
          <div class="form-group">
            <label class="lbl-input" for="company">Company:</label>
            <input type="text" class="form-control txt-input single-field" id="company" name="company">
          </div>
          <div class="form-group">
            <label class="lbl-input" for="location">Location:</label>
            <input type="text" class="form-control txt-input single-field" id="location" name="location" required>
          </div>
          <div class="form-group">
              <label class="lbl-input" for="timezone">Timezone:</label>
              <select class="form-control single-field" id="timezone" name="timezone" required>
                @foreach($timezones as $timezone)
                <option value="{{ $timezone }}">{{ $timezone }}</option>
                @endforeach
              </select>
          </div>
          <div class="form-group">
            <label class="lbl-input" for="prof-pic">Profile Picture:</label>
            <input type="file" class="form-control" id="prof-pic" name="prof-pic">
          </div>
      </div>
      <!--Footer-->
      <div class="modal-footer">
        <button type="button" class="btn btn-med js-btn-cancel btn-red" data-dismiss="modal">Cancel</button>
        <button class="btn btn-med js-btn-add btn-blue btn-red-hover">Update</button>
      </div>
    </div>
  </div>
</div>
<!-- Modal: modalCart -->
<script>
    //load JS functions upon loading
    document.addEventListener('DOMContentLoaded', () => {
        var dqs = (cs) => { return document.querySelector(cs) };
        var dqsa = (cs) =>{ return document.querySelectorAll(cs) };
        var mqs = (cs) => { return document.querySelector('.modal').querySelector(cs) };
        var mqsa = (cs) => { return document.querySelector('.modal').querySelectorAll(cs) };

        //display edit modal
        var showEditModal = (data) => {
            if(data.errors.length !== 0)
                return data.errors.forEach((error) => {
                    //return M.toast({ html: error}); 
                    console.log(error);
                });

            if(data.model === null || data.model === undefined)
                //return M.toast({ html: 'invalid json'});
                console.log('invalid json');            

            mqs('.modal-title').innerHTML =
                'Edit Profile';

            mqs('.js-btn-add').innerHTML =
                'Update';

            mqs('.js-input-id').value = data.model.id;
            mqs('#first_name').value = data.model.first_name;
            mqs('#last_name').value = data.model.last_name;
            mqs('#email').value = data.model.email;
            mqs('#password').value = '';
            mqs('#password2').value = '';
            mqs('#location').value = data.model.location;
            mqs('#timezone').value = data.model.timezone;
            mqs('#occupation').value = data.model.occupation;
            mqs('#company').value = data.model.company;
        };

        //save edits
        var fetchModelSave = () => {
            var modal = dqs('.modal');

            let headers = {};
            headers['X-Requested-With'] = "XMLHttpRequest";

            var data = new FormData();
            data.append('id', mqs('.js-input-id').value);
            data.append('first_name', mqs('#first_name').value);
            data.append('last_name', mqs('#last_name').value);
            data.append('email', mqs('#email').value);
            data.append('password', mqs('#password').value);
            data.append('password2', mqs('#password2').value);
            data.append('location', mqs('#location').value);
            data.append('occupation', mqs('#occupation').value);
            data.append('timezone', mqs('#timezone').value);
            data.append('company', mqs('#company').value);

            fetch("{{ url('/customer/update') }}", {
                headers: headers,
                method: "POST",
                body: data,
                credentials: "same-origin"
            }).then((res) => {
                if(res.status !== 200)
                    console.log('Failed to update customer.');

                return res.json();
            }).then((data) => {
                if(data.errors.length !== 0)
                    return data.errors.forEach((e) => { console.log(e); });

                alert('Successfully Updated Customer Info!');
                mqs('.js-btn-cancel').click();
                location.reload();
            });
        };


        //call AJAX to edit faqs 
        var fetchModelEdit = (id) => {
            let headers = {};
            headers['X-Requested-With'] = "XMLHttpRequest";

            var data = new FormData();
            data.append('id', id);

            fetch("{{ url('/customer/edit') }}", {
                headers: headers,
                method: "POST",
                body: data,
                credentials: "same-origin"
            }).then((res) => {
                if(res.status !== 200)
                    console.log('Failed to edit customer.'); 

                console.log(res.clone().json());
                return res.json();
            }).then((data) => {
                //console.log(data);
                showEditModal(data);
            }).catch((e) => {
                console.log("Error! " + e);
            });
        };


        //add buttons functions
        var setupButtons = () => {
            dqs('.btn-edit').onclick = fetchModelEdit({{ $user->id }});
            dqs('.js-btn-add').onclick = fetchModelSave;
        };

        setupButtons();
    }); 
</script>

CustomerEditController.php

<?php

namespace App\Http\Controllers\Front;

use Illuminate\Http\Request;
use App\Http\Controllers\BaseController as BaseController;

class CustomerEditController extends BaseController
{
    //
    public function handle(Request $request)
    {
        $id = $request->input('id');
        $model = \App\Models\Customers::where('id', $id)->first();

        if($model === null)
            return response()->json(['errors' => ['invalid customer']]);

        return response()->json([
            'model' => $model,
            'errors' => []
        ]);
    }
}

DashboardController.php

<?php

namespace App\Http\Controllers\Front;

use Illuminate\Http\Request;
use App\Http\Controllers\BaseController as BaseController;

class DashboardController extends BaseController
{
    //
    public function handle(Request $request)
    {   
        if(is_null($this->getCurrentUser())){
            return redirect(url('/login'));
        }
        $viewData = [ 'title' => 'Turtl-E | Dashboard',
                      'blog_latest' => $this->getLatestPost(),
                      'header' => $this->getHeader(),
                      'footer' => $this->getFooter(),
                      'config' => $this->getConfig(),
                      'timezones' => $this->getTimezones(),
                      'user' => $this->getCurrentUser(),
                      'orders' => $this->getUserOrders(), ];
        return view($this->getFrontViewGroup() . 'dashboard', $viewData);
    }
}

web.php(路由)

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

/*Route::get('/', function () {
    return view('welcome');
});*/

// prevents unauthorized access
$c = [ \App\Http\Middleware\WebAuthMiddleware::class ];
/*TEST*/
Route::get(  '/test/test2',  'Front\TestController@handle');


/*ERROR PAGE*/
Route::get(  '/error',  'ErrorController@handle');

/*FRONT*/
Route::get(  '/',  'Front\FrontController@handle');

Route::get(  '/blogs',  'Front\BlogListController@handle');
Route::get(  '/blogs/{cat}',  'Front\BlogListController@setActiveCategory');
Route::get(  '/blogs/post/{slug}',  'Front\BlogController@handle');

Route::get(  '/page/{pg_slug}',  'Front\PageController@handle');

Route::get(  '/login',  'Front\LoginController@handle');
Route::post(  '/login',  'Front\LoginController@login');
Route::get(  '/logout',  'Front\LoginController@logout');

Route::post(  '/sign-up',  'Front\SignUpController@handle');

Route::get( '/customer-verify',              'Front\CustomerVerifyController@handle');
Route::post('/customer-resend-verification', 'Front\CustomerResendVerificationController@handle');

Route::get( '/customer-password-reset', 'WebGetPasswordResetController@handle');
Route::post('/customer-password-reset', 'WebPostPasswordResetController@handle');

Route::get(  '/reset-password',  'Front\ResetPasswordController@handle');

Route::get(  '/dashboard',  'Front\DashboardController@handle');

Route::get(  '/create-new-order',  'Front\CreateNewOrderController@handle');

Route::post(  '/customer/edit',  'Front\CustomerEditController@handle')->middleware($c);

Route::post(  '/customer/update',  'Front\CustomerUpdateController@handle')->middleware($c);

/*ADMIN*/

Route::get(  'admin/login',    'Dashboard\DashboardLoginController@handle');
Route::post( 'admin/login',    'Dashboard\DashboardLoginPostController@handle');
Route::get(  'admin/logout',   'Dashboard\DashboardLogoutController@handle');

Route::get(  '/admin',  'Dashboard\DashboardController@handle')->middleware($c);

Route::get(  '/admin/orders',  'Dashboard\OrdersController@handle')->middleware($c);

Route::get(  '/admin/customers',  'Dashboard\CustomersController@handle')->middleware($c);
Route::post(  '/admin/customers/list',  'Dashboard\CustomersListController@handle')->middleware($c);
Route::post(  '/admin/customers/delete-many',  'Dashboard\CustomersDeleteManyController@handle')->middleware($c);

Route::get(  '/admin/administrators',  'Dashboard\AdministratorsController@handle')->middleware($c);
Route::post(  '/admin/administrators/list',  'Dashboard\AdministratorsListController@handle')->middleware($c);
Route::post(  '/admin/administrators/save',  'Dashboard\AdministratorsSaveController@handle')->middleware($c);
Route::post(  '/admin/administrators/edit',  'Dashboard\AdministratorsEditController@handle')->middleware($c);
Route::post(  '/admin/administrators/delete-many',  'Dashboard\AdministratorsDeleteManyController@handle')->middleware($c);

Route::get(  '/admin/services',  'Dashboard\ServicesController@handle')->middleware($c);
Route::post(  '/admin/services/list',  'Dashboard\ServicesListController@handle')->middleware($c);
Route::post(  '/admin/services/save',  'Dashboard\ServicesSaveController@handle')->middleware($c);
Route::post(  '/admin/services/edit',  'Dashboard\ServicesEditController@handle')->middleware($c);
Route::post(  '/admin/services/delete-many',  'Dashboard\ServicesDeleteManyController@handle')->middleware($c);

Route::get(  '/admin/operations/business-hours',  'Dashboard\OperationsBusinessHoursController@handle')->middleware($c);
Route::post(  '/admin/operations/business-hours/list',  'Dashboard\OperationsBusinessHoursListController@handle')->middleware($c);
Route::post(  '/admin/operations/business-hours/save',  'Dashboard\OperationsBusinessHoursSaveController@handle')->middleware($c);
Route::post(  '/admin/operations/business-hours/edit',  'Dashboard\OperationsBusinessHoursEditController@handle')->middleware($c);
Route::post(  '/admin/operations/business-hours/delete-many',  'Dashboard\OperationsBusinessHoursDeleteManyController@handle')->middleware($c);

Route::get(  '/admin/operations/dayoffs',  'Dashboard\OperationsDayoffsController@handle')->middleware($c);
Route::post(  '/admin/operations/dayoffs/list',  'Dashboard\OperationsDayoffsListController@handle')->middleware($c);
Route::post(  '/admin/operations/dayoffs/save',  'Dashboard\OperationsDayoffsSaveController@handle')->middleware($c);
Route::post(  '/admin/operations/dayoffs/edit',  'Dashboard\OperationsDayoffsEditController@handle')->middleware($c);
Route::post(  '/admin/operations/dayoffs/delete-many',  'Dashboard\OperationsDayoffsDeleteManyController@handle')->middleware($c);

Route::get(  '/admin/operations/holidays',  'Dashboard\OperationsHolidaysController@handle')->middleware($c);
Route::post(  '/admin/operations/holidays/list',  'Dashboard\OperationsHolidaysListController@handle')->middleware($c);
Route::post(  '/admin/operations/holidays/save',  'Dashboard\OperationsHolidaysSaveController@handle')->middleware($c);
Route::post(  '/admin/operations/holidays/edit',  'Dashboard\OperationsHolidaysEditController@handle')->middleware($c);
Route::post(  '/admin/operations/holidays/delete-many',  'Dashboard\OperationsHolidaysDeleteManyController@handle')->middleware($c);

Route::get(  '/admin/products',  'Dashboard\ProductsController@handle')->middleware($c);
Route::post(  '/admin/products/list',  'Dashboard\ProductsListController@handle')->middleware($c);
Route::post(  '/admin/products/save',  'Dashboard\ProductsSaveController@handle')->middleware($c);
Route::post(  '/admin/products/edit',  'Dashboard\ProductsEditController@handle')->middleware($c);
Route::post(  '/admin/products/delete-many',  'Dashboard\ProductsDeleteManyController@handle')->middleware($c);

Route::get(  '/admin/file-types',  'Dashboard\FileTypesController@handle')->middleware($c);
Route::post(  '/admin/file-types/list',  'Dashboard\FileTypesListController@handle')->middleware($c);
Route::post(  '/admin/file-types/save',  'Dashboard\FileTypesSaveController@handle')->middleware($c);
Route::post(  '/admin/file-types/edit',  'Dashboard\FileTypesEditController@handle')->middleware($c);
Route::post(  '/admin/file-types/delete-many',  'Dashboard\FileTypesDeleteManyController@handle')->middleware($c);

Route::get(  '/admin/messages',  'Dashboard\MessagesController@handle')->middleware($c);

Route::get(  '/admin/configurations',  'Dashboard\ConfigurationsController@handle')->middleware($c);
Route::post(  '/admin/configurations/list',  'Dashboard\ConfigurationsListController@handle')->middleware($c);
Route::post(  '/admin/configurations/save',  'Dashboard\ConfigurationsSaveController@handle')->middleware($c);
Route::post(  '/admin/configurations/edit',  'Dashboard\ConfigurationsEditController@handle')->middleware($c);
Route::post(  '/admin/configurations/delete-many',  'Dashboard\ConfigurationsDeleteManyController@handle')->middleware($c);

Route::get(  '/admin/cms/header',  'Dashboard\CmsNavbarsController@handle')->middleware($c);
Route::post(  '/admin/cms/header/list',  'Dashboard\CmsNavbarsListController@handle')->middleware($c);
Route::post(  '/admin/cms/header/save',  'Dashboard\CmsNavbarsSaveController@handle')->middleware($c);

Route::get(  '/admin/cms/footer',  'Dashboard\CmsFootersController@handle')->middleware($c);
Route::post(  '/admin/cms/footer/list',  'Dashboard\CmsFootersListController@handle')->middleware($c);
Route::post(  '/admin/cms/footer/save',  'Dashboard\CmsFootersSaveController@handle')->middleware($c);
Route::post(  '/admin/cms/footer/edit',  'Dashboard\CmsFootersEditController@handle')->middleware($c);
Route::post(  '/admin/cms/footer/delete-many',  'Dashboard\CmsFootersDeleteManyController@handle')->middleware($c);

Route::get(  '/admin/cms/sections',  'Dashboard\CmsSectionsController@handle')->middleware($c);
Route::post(  '/admin/cms/sections/list',  'Dashboard\CmsSectionsListController@handle')->middleware($c);
Route::post(  '/admin/cms/sections/save',  'Dashboard\CmsSectionsSaveController@handle')->middleware($c);
Route::post(  '/admin/cms/sections/edit',  'Dashboard\CmsSectionsEditController@handle')->middleware($c);
Route::post(  '/admin/cms/sections/delete-many',  'Dashboard\CmsSectionsDeleteManyController@handle')->middleware($c);
Route::post(  '/admin/cms/sections/sort',  'Dashboard\CmsSectionsSortController@handle')->middleware($c);

Route::get(  '/admin/cms/testimonials',  'Dashboard\CmsTestimonialsController@handle')->middleware($c);
Route::post(  '/admin/cms/testimonials/list',  'Dashboard\CmsTestimonialsListController@handle')->middleware($c);
Route::post(  '/admin/cms/testimonials/save',  'Dashboard\CmsTestimonialsSaveController@handle')->middleware($c);
Route::post(  '/admin/cms/testimonials/edit',  'Dashboard\CmsTestimonialsEditController@handle')->middleware($c);
Route::post(  '/admin/cms/testimonials/delete-many',  'Dashboard\CmsTestimonialsDeleteManyController@handle')->middleware($c);
Route::post(  '/admin/cms/testimonials/sort',  'Dashboard\CmsTestimonialsSortController@handle')->middleware($c);

Route::get(  '/admin/cms/faqs',  'Dashboard\CmsFaqsController@handle')->middleware($c);
Route::post(  '/admin/cms/faqs/list',  'Dashboard\CmsFaqsListController@handle')->middleware($c);
Route::post(  '/admin/cms/faqs/save',  'Dashboard\CmsFaqsSaveController@handle')->middleware($c);
Route::post(  '/admin/cms/faqs/edit',  'Dashboard\CmsFaqsEditController@handle')->middleware($c);
Route::post(  '/admin/cms/faqs/delete-many',  'Dashboard\CmsFaqsDeleteManyController@handle')->middleware($c);
Route::post(  '/admin/cms/faqs/sort',  'Dashboard\CmsFaqsSortController@handle')->middleware($c);

Route::get(  '/admin/cms/top-sliders',  'Dashboard\CmsTopSlidersController@handle')->middleware($c);
Route::post(  '/admin/cms/top-sliders/list',  'Dashboard\CmsTopSlidersListController@handle')->middleware($c);
Route::post(  '/admin/cms/top-sliders/save',  'Dashboard\CmsTopSlidersSaveController@handle')->middleware($c);
Route::post(  '/admin/cms/top-sliders/edit',  'Dashboard\CmsTopSlidersEditController@handle')->middleware($c);
Route::post(  '/admin/cms/top-sliders/delete-many',  'Dashboard\CmsTopSlidersDeleteManyController@handle')->middleware($c);
Route::post(  '/admin/cms/top-sliders/sort',  'Dashboard\CmsTopSlidersSortController@handle')->middleware($c);

Route::get(  '/admin/cms/external-pages',  'Dashboard\CmsExternalPagesController@handle')->middleware($c);
Route::post(  '/admin/cms/external-pages/list',  'Dashboard\CmsExternalPagesListController@handle')->middleware($c);
Route::post(  '/admin/cms/external-pages/save',  'Dashboard\CmsExternalPagesSaveController@handle')->middleware($c);
Route::post(  '/admin/cms/external-pages/edit',  'Dashboard\CmsExternalPagesEditController@handle')->middleware($c);
Route::post(  '/admin/cms/external-pages/delete-many',  'Dashboard\CmsExternalPagesDeleteManyController@handle')->middleware($c);
Route::post(  '/admin/cms/external-pages/get-category',  'Dashboard\CmsExternalPagesGetCategoryController@handle')->middleware($c);

Route::get(  '/admin/cms/categories',  'Dashboard\CmsCategoriesController@handle')->middleware($c);
Route::post(  '/admin/cms/categories/list',  'Dashboard\CmsCategoriesListController@handle')->middleware($c);
Route::post(  '/admin/cms/categories/save',  'Dashboard\CmsCategoriesSaveController@handle')->middleware($c);
Route::post(  '/admin/cms/categories/edit',  'Dashboard\CmsCategoriesEditController@handle')->middleware($c);
Route::post(  '/admin/cms/categories/delete-many',  'Dashboard\CmsCategoriesDeleteManyController@handle')->middleware($c);


/*Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');*/

0 个答案:

没有答案