1-首先,您需要创建路线:
Ajax Request handling:
pattern: /ajax/call1
defaults: { _controller: MOBILEBIBundle:Web:ajax_call1 }
2-在你的控制器中创建一个名为:ajax_call1的函数我的情况我有(Web):
public function ajax_call1Action(){
$request = Request::createFromGlobals();
$user = $request->request->get('user');
$em = $this->getDoctrine()->getmanager();
$all_users = $em->getRepository('MOBILEBIBundle:Service')->findByUser($user);
$user_service = array();
foreach($all_users as $single_user){
$user_service[$single_user->getId()]=$single_user->getDescription();
}
$response = array("code" => 100, "success" => true, "user_service"=>$user_service);
return new Response(json_encode($response));
}
3-在你的twig文件中创建一个jquery函数,它将在更改下拉列表中发送ajax请求
$(function(){
$(".select-user").change(function(){
$userval = $(".select-user").val();
$.post('{{path('Ajax Request handling')}}',
{user: $userval},
function(response){
if(response.code == 100 && response.success){
$('.select-parent').find('option').remove();
$.each(response.user_service, function(key, value) {
$('.select-parent')
.append($("<option></option>")
.attr("value",key)
.text(value));
});
}
}, "json");
});
});
4-两次下降:
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Select User: </label>
<br/>
{{ form_widget(form.user, {'attr':{'class':'select-user form-control'}}) }}
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Select Parant Service: </label>
<br/>
{{ form_widget(form.parent, {'attr':{'id':'selectparent', 'class':'select-parent form-control'}}) }}
</div>
</div>
</div>