我有打印动作,从db
获取我的所有记录public function printAction()
{
$users = $this->getDoctrine()->getRepository('ModelBundle:Users')->findAll();
$resp = new JsonResponse($users, 200);
return $resp;
}
我想使用这些数据并通过div元素中的ajax打印,但我无法理解,我该怎么做。也许有人知道。求你帮帮我。
答案 0 :(得分:0)
假设在您看来,
<div class="dynamic-data">
</div>
$.ajax({
url: "path to your print function",
type: "POST",
dataType: "HTML",
async: false,
data: {"u": url},
success: function(data) {
$(".dynamic-data").html(data);
// here directly manipulate the data in controller or get the data in success function and manipulate .
}
});
在打印功能中而不是返回打印数据
答案 1 :(得分:0)
使用jquery ajax()函数将数据呈现为html标记。最好的方法是创建一个通用的方法如下,并使用url和div id对其进行分类
function renderPartialInDiv(url, divID) {
$.ajax({
cache: false,
async: true,
type: "POST",
url: url,
data: null,
success: function (data) {
$(divID).html(data);
},
processData: false,
async: false
});
答案 2 :(得分:0)
您的用户实体中是否有序列化程序?因为您将所有用户都视为实体。我建议你做这样的事情:
当您点击按钮或任何元素时,请按照以下方式调用您的路线:
//change this element to your button
$('a.press-me').click(function() {
$.ajax({
url: 'YOUR ROUTE HERE',
dataType: 'HTML',
success: function (data) {
$('#your-div').html(data);
}
});
});
//create a view users.html.twig or something like that...
{% if users is defined and users is not empty %}
{% for user in users %}
Name: {{ user.name }}
{% endfor %}
{% else %}
<p class="error">No data!</p>
{% endif %}
//add this line to top of your controller
use Symfony\Component\HttpFoundation\Request;
//add request variable to your action
public function printAction(Request $request)
{
//you want to get users via ajax right? so check if the request is ajax or not
if($request->isXmlHttpRequest()) {
// Get all users
$users = $this->getDoctrine()->getRepository('ModelBundle:Users')->findAll();
//render a view and pass it as variable
return $this->renderView('ModelBundle:Default:users.html.twig', ['users'] => $users);
}
}