Laravel如何将请求后的数组值填充到模态中



嗨,我目前正在做一个预约表单,用户可以在其中选择他想要预约的日期和时间范围。我想在点击搜索按钮时在模态上显示结果数组,并将模态上的结果数组填充为

@forelse($dt作为$dt(。

下面是我的blade.php视图页面:

@section('content')
<div class="card-body">
<form action="{{ route('assistant.newappts.new') }}" method="POST">
@method('post')
@csrf
<label for="select_date">Select Date:</label>
<input type="text" id="select_date" class="form-control" name="select_date" placeholder="Select Date">
<div class="spacer"></div>
<div class="half-form">
@foreach ($operatinghrs as $operatinghr)
<div class="form-group">
<label for="starttime">Choose Start Time </label>
<br>
<input type="time" id="start_time" name="start_time" min="{{display24HTime($operatinghr->start_time)}}" max="{{display24HTime($operatinghr->end_time)}}" value="{{ display24HTime(old('start_time', $operatinghr->start_time))}}">
</div>
<div class="form-group">
<label for="starttime">Choose End Time</label>
<br>
<input type="time" id="end_time" name="end_time" min="{{display24HTime($operatinghr->start_time)}}" max="{{display24HTime($operatinghr->end_time)}}" value="{{ display24HTime(old('end_time', $operatinghr->end_time))}}">
<div class="form-update" style="float:right;">
<button type="button" class="btn btn-primary" data-toggle="modal" id="find_appointment_btn">Search</button>
</div>
</div>
@endforeach             
</div>
<div class="spacer"></div>
</form>
</div>
@overwrite
@section('modal')
<!-- MODAL NEW APPOINTMENT -->
<div class="modal fade" id="myModalNewAppointment">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Select Appointment</h4>
</div>
<!-- Modal body -->
<div class="modal-body">
<div class="form-group">
<div class="timeslots-section">
<div class="timeslots text-center">
@forelse ($dt as $dt)
<div class="timeslot">
<input type="checkbox" class="timeslotchk" name="timeslot" value="{{$dt}}">
{{$dt}}
</div>
@empty
<div class="empty" style="text-align: left">No appointments available.</div>
@endforelse
</div> <!-- end timeslots -->
</div>
</div>

</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="new_appt_save_btn" data-loading-text="<i class='fa fa-spinner fa-spin'></i> saving..">Save</button>
<button type="button" class="btn btn-outline-primary" id="close_btn" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
@overwrite

下面是我为blade.php视图页面编写的javascript

<script>
$(document).ready(function() {
$('#select_date').datepicker({      
dateFormat: "dd-mm-yy",
changeMonth: true,
changeYear: true,
todayHighlight: true,
toggleActive: true
}); 
$('#find_appointment_btn').click(function() {
$('#myModalNewAppointment').modal({backdrop: 'static', keyboard: false});
$('#myModalNewAppointment .modal-title').html('New Appointment');
});
})
</script>

下面是我在页面上加载的控制器类方法和获取预约时间的后请求方法:

public function index()
{
if ($_SESSION['user_role'] != 'Assistant') {
return "Unauthorized Access";
}
$workinghr = WorkingHour::where('clinic_id', $_SESSION['clinic_ID'])->where('off_day', false)->pluck('day')->toArray();

$todayday = Carbon::now('Asia/Singapore')->format('l');
$operatinghrs = $this->getWorkDayTiming($todayday);
$data = [
'link_menu_appt' => 'open active',
'link_newappt' => 'active',                       
'operatinghrs' => $operatinghrs,            
];
return view('patient_appointment.available-appointment', $data);
}
public function filterByDate(Request $request)
{
$dateselected = $request->select_date;
$starttime = $request->start_time;
$endtime = $request->end_time;

$dtarray = $this->getSelectedDate($dateselected, $starttime, $endtime);
$dt = array_slice($dtarray, 0, 12, true);
$todayday = Carbon::now('Asia/Singapore')->format('l');
$operatinghrs = $this->getWorkDayTiming($todayday);

$data = [
'link_appt' => 'active',                   
'operatinghrs' => $operatinghrs,       
'dt' => $dt,                
];
return view('patient_appointment.available-appointment', $data);
}

对于JS部分,您必须执行以下操作:您将获得输入字段的所有数据,并通过ajax请求将其发送到您定义的路由。(别忘了csrf代币(

<script>
$("#find_appointment_btn").click(function(event){
event.preventDefault();
let start = $("input[name=start_time]").val();
let end = $("input[name=end_time]").val();
let date = $("input[name=date]").val();
let _token   = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url: "/YOUR_URL_HERE",
type:"POST",
data:{
start_time:start,
end_time:end,
date: date,
_token: _token
},
success:function(response){
console.log(response);
//display the result if no error occurred with help of JS
},
});
});
</script>

在您的控制器中,您可以做与以前相同的事情,但您必须返回一个响应:


public function filterByDate(Request $request)
{
$dateselected = $request->select_date;
$starttime = $request->start_time;
$endtime = $request->end_time;

$dtarray = $this->getSelectedDate($dateselected, $starttime, $endtime);
$dt = array_slice($dtarray, 0, 12, true);
$todayday = Carbon::now('Asia/Singapore')->format('l');
$operatinghrs = $this->getWorkDayTiming($todayday);

$data = [
'link_appt' => 'active',                   
'operatinghrs' => $operatinghrs,       
'dt' => $dt,                
];
return response->json($data, 200);
}

我希望这能引导你朝着正确的方向前进

您最好可以通过Axios使用Laravel API调用来实现这一点,Axios是一个轻量级的javascript库,使您能够执行AJAX操作,而不必承担加载Jquery这样的重量级库的负担(即,如果您要使用的只是进行AJAX调用(。

创建Laravel API路由与创建LaravelWeb路由完全相同。唯一的区别是您创建的API路由位于yourdomain.com/api/{route-url}而不是yourdomain.com/{route-url}下。

设置好API后,可以使用Postman这样的简单API测试客户端来确保API返回预期结果。

现在剩下的就是通过Axios向API发出XML-HTTP请求。

您可以在项目根目录中的终端上运行以下命令(假设您已经安装了节点(,将axios作为项目的依赖项进行安装和注入:

npm install           //install dependencies listed in your package.json
npm install axios     //install axios if it is not listed in your package.json

您可以在package.json文件(在项目根目录中(中检查现有的节点依赖关系。

一旦您对依赖项进行了排序,您可以简单地将Axios导入到JS文件中,如下所示:

import axios from 'axios'

现在我们都准备好了,每次单击表单提交或加载按钮或任何JS事件,您都可以使用axios.get()axios.post()axios.put()axios.delete()方法触发Axios XML-HTTP请求。

典型的Javascript Axios请求如下所示:

axios.<request type, i.e. get, post etc>('<request url>' + <wild card query data>,
{
//parse & manipulate data
})
.then(response =>
{
if(check if response was successful)
{
//trigger some event like page reload or show the modal in your case
}
}
.catch(error => 
{
//handle error
})

最新更新