2017-05-30 4 views
0

私はLaravel/JQueryで私は中程度だと言って始めましょう。私の質問に耐えてください。LaravelのAjaxリクエストで意見を返す方法

ユーザーがボタンをクリックしたときに、ajaxを使用してビューを返したいとします。ボタンをクリックするたびに、エラーは表示されませんが、HTMLも表示されません。どんな助けもありがとうございます。

私のようにweb.php私のルートを定義しました。私のsection2_formビューがどのように見える

<html> 
<head> 
    <meta name="csrf-token" content="{{ csrf_token() }}"> 
    <title>Ajax Example</title> 

    <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> 
    </script> 

    <script> 
     function getMessage() { 
      $.ajaxSetup({ 
       headers: { 
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') 
       } 
      }); 
      $.ajax({ 
       type: 'POST', 
       url: '/getmsg', 
       data: '_token = <?php echo csrf_token() ?>', 
       success: function (data) { 

        $("#msg").html(data.html); 
       } 
      }); 
     } 
    </script> 
</head> 

<body> 
    <div id = 'msg'>This message will be replaced using Ajax. 
     Click the button to replace the message.</div> 
    <form> 
     <button onclick="getMessage()">Replace Message</button> 
    </form> 
</body> 

:よう

Route::get('ajax', function() { 
    return view('test'); 
}); 

Route::post('/getmsg', function() { 
    $msg = "<strong>This is a simple message.</strong>"; 
    $returnHTML=view('form1_sections/section2_form')->render(); 
    return response()->json(array('html'=>$returnHTML, 'msg'=>$msg)); 
}); 

マイtest.blade.phpが見えます:

にリクエストの dataTypeを設定し
<div class="well"> 
<div class="row"> 
    <div class="col-xs-12"> 

     <h4>Date of Previous Research Leave</h4> 
     <br> 
     <label>Start Date:</label> 
     <label> 
      <input class="form-control" name="startDate" id="startDate" placeholder="Start Date" type="date"> 
     </label> 
     <br><br> 
     <label>End Date:</label> 
     <label> 
      <input class="form-control" name="endDate" id="endDate" placeholder="End Date" type="date"> 
     </label> 
    </div> 
</div> 

+0

成功関数の中の 'console.log(data)'の結果は何ですか? –

答えて

0

。また、あなたのtokenのあなたの建設はよく、それは間違っていないですが、良い方法があります、完全な答えのために、以下を守って、次のとおりです。

$.ajax({ 
    type: 'POST', 
    url: '/getmsg', 
    data: { 
     token: $('meta[name="csrf-token"]').content() 
    }, 
    dataType: 'json', 
    success: function (data) { 
     $("#msg").html(data.html); 
    } 
}); 

それはjsonにする必要がある理由は、それ以外の要求は応答があると仮定しているtext/html 。つまり、返されたデータにはJSON.parse()が呼び出されないので、プロパティにアクセスできるオブジェクトはありません。

+0

No luck:/何もロードしません。 – Muhammad

関連する問題