2017-05-30 119 views
0

让我首先说我是Laravel/JQuery中的一员,请耐心等待我的问题。如何在Laravel的Ajax请求中返回视图

我想在用户单击按钮时使用ajax返回视图。每当我点击按钮,我收到没有错误,但也没有得到任何HTML。任何帮助表示赞赏。

我定义我的路线web.php为:

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样子:

<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> 

我section2_form观点看起来像:

<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

设置你的请求dataTypejson。另外你对你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

不运气:/它不加载任何东西。 – Muhammad