我有一个字段(称为名称),每当我在此字段中写入时,ajax脚本(实时搜索将数据从twig发送到控制器而不重新加载)检查数据是否已存在或未显示消息。我的问题是我不能为这个字段设置一个名字,我试过这个但它不起作用
{{ form_label(form.name) }}
{{ form_widget(form.name,{'id':'name','attr':{'name':'name'}}) }}
{{ form_errors(form.name) }}
这里我在控制器中的功能,我确信它能正常工作,
public function searchBackTeamAction(Request $request)
{
if($request->isXmlHttpRequest())
{
$serializer = new Serializer(array(new ObjectNormalizer()));
$em = $this->getDoctrine()->getManager();
$teams= $em->getRepository('TeamBundle:Team')->findOneBy(['name'=>$request->get('name') ]);
$data = $serializer->normalize($teams);
return new JsonResponse($data);
}
}
这是我的脚本我也确定它能正常运行
<script>
$(document).ready(function () {
$("#name").keyup(
function(){
$.ajax({
url: "{{ path('team_searchBack') }}",
data: $("#name").serialize(),
type:"POST",
success: function (data, status, object) {
console.log(data);
if(data.name != null)
{
$("#error_login").css('display','block');
$("#submit").prop('disabled', true);
}
else
{
$("#error_login").css('display','none');
$("#submit").prop('disabled', false);
}
},
error: function(req, textStatus, errorThrown,data) {
//this is going to happen when you send something different from a 200 OK HTTP
console.log('Ooops, something happened: ' + textStatus + ' ' +errorThrown);
},
complete: function() {
// Runs at the end (after success or error) and always runs
}
});
})
}
);
</script>
你能帮我吗?
答案 0 :(得分:0)
使用以下javascript
<script>
$(document).ready(function () {
$("#name").keyup(
function(){
$.ajax({
url: "{{ path('team_searchBack') }}",
data: {"name": $("#name").val()},
type:"POST",
success: function (data, status, object) {
console.log(data);
if(data.name != null)
{
$("#error_login").css('display','block');
$("#submit").prop('disabled', true);
}
else
{
$("#error_login").css('display','none');
$("#submit").prop('disabled', false);
}
},
error: function(req, textStatus, errorThrown,data) {
//this is going to happen when you send something different from a 200 OK HTTP
console.log('Ooops, something happened: ' + textStatus + ' ' +errorThrown);
},
complete: function() {
// Runs at the end (after success or error) and always runs
}
});
})
}
);