javascript - 使用 ajax+js 在 symfony4 中进行实时搜索
问题描述
我想在 symfony 4 下实现实时搜索,但我卡住了。我希望你的帮助朋友。
我的控制器
/**
* @Route("/search", name="search")
*/
public function searchAction(Request $request){
$user = new User();
$searchTerm = $request->query->get('search');
$em = $this->getDoctrine()->getManager();
$results = $em->getRepository(User::class)->findOneBy(['email' => $searchTerm]);
//$results = $query->getResult();
$content = $this->renderView('search.html.twig', [
'res' => $results,
'val' => $searchTerm
]);
$response = new JsonResponse();
$response->setData(array('list' => $content));
return $response;
}
我的脚本 ajax 这是我的 ajax 脚本
$.ajax({
type: "GET",
url: "{{ path('search') }}",
dataType: "json",
data: {search: input},
cache: false,
success: function (response) {
$('.example-wrapper').replaceWith(response);
//$('.example-wrapper').load("{{ path('search') }}?search="+ $search.val());
console.log(response);
},
error: function (response) {
console.log(response);
}
});
search.html.twig
<form class="example-wrapper" role="search" method="post" action="{{ path('search') }}">
<div>
<input type="text" class="form-control" name="search" value="{{ val }}">
<button type="submit" class="btn btn-success" name="sub">search</button>
</div>
</form>
<div class="example-wrapper">
{% for result in res %}
<p style="display:inline-block;width:200px;">{{ result.fullname }}</p>
<p style="display:inline-block;width:100px;">{{ result.username }}</p>
<p style="display:inline-block;width:300px;">{{ result.email }}</p>
<p style="display:inline-block;width:120px;">{{ result.roles[0] }}</p>
{% endfor %}
</div>
搜索页面看起来像我看不到表单,除非取消 ajax 脚本
解决方案
你很近。:) 就我个人而言,我会做这样的事情。
动作功能:
/**
* Search action.
* @Route("/search/{search}", name="search")
* @param Request $request Request instance
* @param string $search Search term
* @return Response|JsonResponse Response instance
*/
public function searchAction(Request $request, string $search)
{
if (!$request->isXmlHttpRequest()) {
return $this->render("search.html.twig");
}
if (!$searchTerm = trim($request->query->get("search", $search))) {
return new JsonResponse(["error" => "Search term not specified."], Response::HTTP_BAD_REQUEST);
}
$em = $this->getDoctrine()->getManager();
if (!($results = $em->getRepository(User::class)->findOneByEmail($searchTerm))) {
return new JsonResponse(["error" => "No results found."], Response::HTTP_NOT_FOUND);
}
return new JsonResponse([
"html" => $this->renderView("search.ajax.twig", ["results" => $results]),
]);
}
您search.html.twig
不应该包含带有结果的 for 循环,而应该只是 this 而不是 for 循环:
<form id="search-form" class="example-wrapper" role="search" method="get" action="{{ path('search') }}">
<div>
<input type="text" class="form-control" name="search">
<button type="submit" class="btn btn-success" name="sub">search</button>
</div>
</form>
<div id="search-results" class="example-wrapper"></div>
<script type="text/javascript"><!--
jQuery(document).ready(function($){
$('#search-form').submit(function(e){
e.preventDefault();
$('#search-results').html("");
$.get("{{ path('search') }}/" + input, function(data, textStatus, xhr){
if ("object" !== typeof data || null === data) {
alert("Unexpected response from server.");
return;
}
if (!data.hasOwnProperty("html") || typeof data.html != "string" || (data.html = data.html.trim()).length < 1) {
alert("Empty response from server.");
return;
}
$('#search-results').html(data.html);
}).fail(function(xhr, textStatus, errorThrown){
var error = "Unknown error occurred.";
if ("object" === typeof xhr && null !== xhr && xhr.hasOwnProperty("responseJSON") && "object" === typeof xhr.responseJSON && xhr.responseJSON.hasOwnProperty("error") && "string" === typeof xhr.responseJSON.error && xhr.responseJSON.error.trim().length >= 1) {
error = xhr.responseJSON.error.trim();
} else if ("string" === typeof errorThrown && errorThrown.trim().length >= 1) {
error = errorThrown.trim();
}
alert(error);
});
});
});
--></script>
然后,您应该search.ajax.html
在同一个文件夹中search.html.twig
包含结果循环。这应该只包括:
{% if results is defined and results is iterable and results|length >= 1 %}
{% for result in results %}
<p style="display:inline-block;width:200px;">{{ result.fullname }}</p>
<p style="display:inline-block;width:100px;">{{ result.username }}</p>
<p style="display:inline-block;width:300px;">{{ result.email }}</p>
<p style="display:inline-block;width:120px;">{{ result.roles[0] }}</p>
{% endfor %}
{% endif %}
推荐阅读
- reactjs - 如何将图像下载到“reactjs src 文件夹”
- java - 序列化和反序列化二叉树
- c# - 调用安全的 ASP.NET Core 5 Web API 会导致 HTTP 406 - Not Acceptable 错误
- python - Discord bot 命令随机停止与 python 一起工作?
- docker - 在 URL (ip:port) 上全局访问 docker 应用程序
- c# - 按钮事件将创建一个文件夹以及子文件夹
- java - 从其他受密码保护的存储库中导入 Maven 依赖项
- python-3.x - 在 Raspberry Pi 3 上使用 pymssql 的 SQL Server 连接
- nlme - 校正空间自相关(GLS,nlme 包)
- lucene.net - 如何使用 Lucene dotnet 4.8.0 实现 Lucene dotnet 语音分析器?