我有一個Symfony應用程序,它允許在某些事件上執行CRUD操作,並且還可以搜索它們。我得到的問題是在試圖獲得我正在搜索的結果而不刷新頁面時顯示的問題。這是我第一次使用ajax,我認爲它的功能有問題。當我搜索任何事件名稱中的單詞時,頁面不會刷新,並且顯示未定義,而不顯示條目。 我感謝任何幫助!通過ajax調用搜索結果時獲取undefined
下面是來自控制器的方法:
public function ajaxListAction(Request $request){
//fetch the data from the database and pass it to the view
$em = $this->getDoctrine()->getManager();
$searchTerm = $request->get('search');
$form = $this->createFormBuilder()
->add('search', SubmitType::class, array('label' => 'Search', 'attr' => array('class' => 'btn btn-primary', 'style' => 'margin-bottom:15px')))->getForm();
$organizer = array();
if($searchTerm == ''){
$organizer = $this->getDoctrine()->getRepository('AppBundle:Organizer')->findAll();
}
elseif ($request->getMethod() == 'GET') {
$form->handleRequest($request);
$em = $this->getDoctrine()->getManager();
$organizer = $em->getRepository('AppBundle:Organizer')->findAllOrderedByName($searchTerm);
}
$response = new JsonResponse();
$results = array();
foreach ($organizer as $value) {
$results[] = json_encode($value);
}
return $response->setData(array(
'results' => $results
));
}
,這裏是搜索的腳本:
$(document).ready(function(event) {
$("#search").submit(function(event) {
event.preventDefault(); //prvent default submission event
$form = $(this);
var data = $('#search_term').val();
$.ajax({
url: '/ajax',
type: "GET",
data: {'search' : data },
success: function(response){
var output = '';
for (var i = 0; i < response.length; i++) {
output[i] = output + response;
}
$('#ajax_results').html('<tr><td>' + response.id + '</td></tr>' + '<tr><td>' + response.name + '</td></tr>' + '<tr><td>' + response.dueDate + '</td></tr>');
}
})
});
});
和用於顯示數據的index.html.twig文件:
{% extends 'base.html.twig' %}
{% block body %}
<h2 class="page-header"> Latest events </h2>
<form id="search" method="GET" action="">
<input type="text" name="search" id="search_term" />
<input type="submit" name="submit" value="Search" />
</form>
<hr />
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>Event</th>
<th>Due Date</th>
<th></th>
</tr>
</thead>
<tbody id="ajax_results">
{% for Events in organizer %}
<tr>
<th scope="row">{{Events.id}}</th>
<td>{{Events.name}}</td>
<td>{{Events.dueDate|date('j F, Y, g:i a')}}</td>
<td>
<a href="/organize/details/{{Events.id}}" class="btn btn-success">View</a>
<a href="/organize/edit/{{Events.id}}" class="btn btn-default">Edit</a>
<a href="/organize/delete/{{Events.id}}" class="btn btn-danger">Delete</a>
</td>
</tr>
{% endfor %}
<table class="table table-striped">
{% if organizer|length > 0 %}
{% for items in organizer %}
{% endfor %}
{% else %}
<tr>
<td colspan="2">No matching results found!</td>
</tr>
{% endif %}
</table>
</tbody>
</table>
{% endblock %}
您將'output'定義爲字符串,然後執行'output [i] = output'?這是行不通的。 – Jeff
是的,謝謝!我已經看到我做了一個小菜一碟的錯誤。 – Dutchman08