Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/436.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用ajax+;js_Javascript_Ajax_Symfony_Doctrine Orm_Symfony4 - Fatal编程技术网

Javascript 使用ajax+;js

Javascript 使用ajax+;js,javascript,ajax,symfony,doctrine-orm,symfony4,Javascript,Ajax,Symfony,Doctrine Orm,Symfony4,我想在symfony 4下实现实时搜索,但我被卡住了。 我希望你能帮助我的朋友 我的控制器 /** * @Route("/search", name="search") */ public function searchAction(Request $request){ $user = new User(); $searchTerm = $request->query->get('search'); $em = $t

我想在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


搜索
{%res%中的结果为%res}

{{result.fullname}

{{result.username}

{{result.email}

{{result.roles[0]}}

{%endfor%}
搜索页面看起来好像我看不到表单,除非去掉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循环,而应仅包含以下内容,而不是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>

hey adambean非常感谢您的帮助,但仍然存在问题:(1/4)ResourceNotFoundException(2/4)NotFoundHttpException未找到“获取/搜索”的路由(3/4)错误类“App\Controller\ExceptionController”未找到(4/4)InvalidArgumentException控制器“App\Controller\ExceptionController”既不作为服务也不作为类存在。如果您有任何想法,请告诉我其他人给我发送电子邮件,我想问您。ResourceNotFoundException:这可能是因为“search.html.twig”缺失或“search.ajax.twig”缺失。NotFoundHttpException:更改
公共函数searchAction(Request$Request,string$search)
to
public function searchAction(Request$Request,string$search=null)
No,这与社区讨论的堆栈交换精神背道而驰。请将此公开供公众讨论和贡献。
<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>
{% 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 %}