2017-01-04 166 views
1

我有一個laravel應用程序部署在我的服務器上。laravel ajax共享主機

文件結構

server 
│ 

└───blog-app 
│ │ app 
│ │ bootstrap 
│ │ ...... 
│ 
└───public_html 
    │ blog 
    │  │─── index.php 
    │ 

這是我的結構是什麼樣子。直到現在一切似乎都正常,但是現在我試圖對我的控制器功能進行AJAX調用,但它不能正常工作。

讓我用一個例子解釋,

$.ajax({ 
    type:'POST', 
    url:'{{route('blog.prefetchResults')}}', 
    data:'_token = <?php echo csrf_token() ?>', 
    success:function(data){ 
       $("#msg").html(data.msg); 
      } 
    }); 

這是我的AJAX調用都到它指向駐留在BlogController控制器的路線blog.prefetchResults。然而,當我看在瀏覽器控制檯我看到這種類型的錯誤:

http://mysubdomain.com/blog/[email protected] 500 (Internal Server Error)

我可以從這個錯誤推斷的是,它不允許當客戶端請求讓我來訪問這些目錄,這使得我問一個非常簡單的問題:如果我不能這樣做,我該如何使用laravel發出AJAX請求?

更新(例如):

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

test.blade.php

@extends('main') 
<p> 
This is an ajxax test 
</p> 
<button class="butt"> 
    click me 
</button> 
<script> 
    $().ready(function(){ 
     $('butt').on('click',function(){ 
       $.ajax({ 
       type:'GET', 
       url:'{{route('blog.test')}}', 
       success:function(data){ 
          $("p").html("somthing"); 
         } 
       }); 
     }) 
    }); 
</script> 

Web.php

//Test controller 
Route::get('blog/test'.'[email protected]')->name('blog.test'); 

BlogController

public function test(){ 
     return view('test.test')->withMessage('changed'); 
    } 

文件結構

文件結構

server 
    │ 

    └───blog-app //Not accessible through client side languages 
    │ │ app->Http->Controllers/BlogController.php 
    │ │ resources->views->test->test.blade.php 
    │ │ routes->web.php->route defined here 
    │ 
    └───public_html(www folder)// accessible to the client (www.mydomain.com) 
     │ blog 
     │  │─── index.php 
     │ 

@Alejandro回覆

  • 校正了上述問題。
  • 對不起關於app->Http->BlogController.php,它是app->Http->Controllers/BlogController.php

注:

  • public_html目錄是根目錄,這是對我的mydomain.com根點。

  • 所以其他文件夾如blog-app對於普通用戶來說是不可訪問的,它們只能被服務器端語言訪問。

日誌文件

[2017-01-08 19:23:01] local.ERROR: exception 'ErrorException' with message 
'Trying to get property of non-object' in 
/home/mydomainuser/blogapp/storage/framework/views/af6b0045a9d30a80c19dd552032d46b39ad1cc99.php:1 



Next exception 'ErrorException' with message 
'Trying to get property of non-object (View: /home/foodq7y4/blogapp/resources/views/blog/single.blade.php)' in 
/home/mydomainuser/blogapp/storage/framework/views/af6b0045a9d30a80c19dd552032d46b39ad1cc99.php:1 

的.htaccess

<IfModule mod_rewrite.c> 
    <IfModule mod_negotiation.c> 
     Options -MultiViews 
    </IfModule> 

    RewriteEngine On 

    # Redirect Trailing Slashes If Not A Folder... 
    RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteRule ^(.*)/$ /$1 [L,R=301] 

    # Handle Front Controller... 
    RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteRule^index.php [L] 

    # Handle Authorization Header 
    RewriteCond %{HTTP:Authorization} . 
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] 
</IfModule> 

Single.blade.php

@extends('main') 

@section('title', '| Blog') 

@section('content') 


    <div class="row"> 
     <div class="col-md-8 col-md-offset-2"> 
      <h1>Blog</h1> 
     </div> 
    </div> 

    @foreach ($posts as $post) 
    <div class="row"> 
     <div class="col-md-8 col-md-offset-2"> 
      <h2>{{ ucwords($post->title) }}</h2> 
      <h5>Published: {{ date('M j, Y', strtotime($post->created_at)) }}</h5> 

      <p>{{ substr(strip_tags($post->body), 0, 250) }}{{ strlen(strip_tags($post->body)) > 250 ? '...' : "" }}</p> 

      <a href="{{ route('blog.single', $post->slug) }}" class="btn btn-sm btn-primary">Read More</a> 
      <hr> 
     </div> 
    </div> 
    @endforeach 

    <div class="row"> 
     <div class="col-md-12"> 
      <div class="text-center"> 
       {!! $posts->links() !!} 
      </div> 
     </div> 
    </div> 


@endsection 
+0

嘗試使用URL的實際路徑,而不是路由 – GabMic

+0

它不會工作,要麼導致該目錄只與服務器端訪問 –

+0

客戶端只被允許的的public_html –

回答

3

您是否嘗試過使用瀏覽器直接訪問網址? 鑑於您正在獲得「500(內部服務器錯誤)」,我將首先檢查服務器日誌。然而 有些事情,:

  • 你應該調用元素類:$('.butt'),但我想你明白我的。

  • 您不需要爲GET請求傳遞csrf標記。除非你想做一些自己的驗證/授權。對於POST請求,Laravel將檢查令牌。您可以使用ajax選項headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}'}在HTTP標頭中發送它。

  • 如果要將數據作爲純字符串發送,請刪除空格:data:'_token=<?php echo csrf_token() ?>',否則該字段最終會被設置爲_token_

  • 不過,我認爲這是更好地設置請求數據作爲JS對象:{'_token': '{{ csrf_token() }}'}

  • 你說你的文件結構具有app->Http->BlogController.php。默認情況下,Laravel希望控制器位於app/Http/Controllers目錄中。

  • 它看起來像控制器返回一個html字符串,所以data.msg可能返回undefined。相反,data是html字符串。

試着修復這些東西,然後評論或編輯跟進。


更新: 從服務器日誌,我們發現這個問題是views/blog/single.blade.php。你已經知道這是$posts->links,顯然帖子不是一個對象。

+0

我已更新我的問題,請看看。 –

+0

我已更新我的問題與日誌文件內容,希望這可以幫助 –

+0

@BOTJr。好吧,它看起來像一些對象在視圖'blog.single'中爲null。你可以發佈,如果你想這樣我們可以看看 – alepeino

0

在做AJAX請求時,請記住始終使用response()->json()方法返回JSON響應,而不是使用類似於您的BlogController test()方法示例中的視圖。

另外,在您的管理面板中實施類似LogViewer的內容(如果有的話)可以查看日誌文件並閱讀發生的錯誤。設置Bugsnag也不是一個壞主意。

+0

讓我上傳日誌文件內容以及 –

+0

我已更新我的問題。 –

+0

某些對象爲空,這就是爲什麼你在視圖中得到這個錯誤,但正如我所說的,當使用AJAX請求時,你不應該返回一個視圖,只有JSON響應是有效的。 – Ruffles

0

在應用程序中,這是工作很好。像這樣更改您的代碼:

1。查看部分

<p id="response"></p> 
     <button class="butt"> 
      click me 
     </button> 
     <script> 
      $(document).ready(function(){ 
       $('.butt').on('click',function(){ 
        $.ajax({ 
         dataType:'HTML', 
         type:'GET', 
         url:'{{route('blog.test')}}', 
         success:function(data){ 
          $("#response").html(data); 
         } 
        }); 
       }) 
      }); 
     </script> 

2.Controller部分

public function test() 
    { 
     return \View::make('test.test')->withMessage('changed'); 
     //or return view()->withMessage('changed'); 
    } 

而對於之後該網絡時,你會點擊按鈕功能打開控制檯,依次單擊它會告訴你的紅色鏈接,如果有錯誤

  1. 點擊該鏈接
  2. 在控制檯頂部的選項卡列表中查找預覽(並顯示服務器端錯誤)。

好運

0

你的JavaScript

發送HTTP請求到實際的路線,而不是指定的路線爲我工作。

$().ready(function(){ 
    $('.butt').on('click',function(){ 
      $.ajax({ 
       method: 'GET', 
       dataType:'json', 
       url:'/blog/test', 
       success: function(data){ 
        console.log(typeof(data)) // see Object {} 
       } 
      }); 
    }) 
}); 

BlogController

JSON響應應AJAX請求來生成。

public function test(){ 
    return response() 
     ->json(['type' => 'Test', 'message' => 'It works!']); 
} 

CSRF保護

這裏的許多選項。我個人最喜歡的:

<meta name="csrf-token" content="{{ csrf_token() }}">