在我看来,我将Ajax POST请求和数据一起发送到控制器。然后,在控制器中,它将接收数据并将其作为输入放入选择查询中以从数据库获取数据。然后,它将从数据库接收的数据发送到视图以显示。
if( $this->request->is('ajax') ) {
$this->autoRender = false;
print_r($this->request->data);
// get values from Ajax POST request here
$from=( $this->request->data('start_time'));
$from = date('Y-m-d', strtotime($from));
$to= $this->request->data('end_time');
$to = date('Y-m-d', strtotime($to));
//put data to a select query
.....
//put all data received from database into $products
$products = $this->Order->find('all',$option);
Debugger::dump($products);
//send data to the view.
$this->set('products',$products);
//}
}
我在$ products中获得了所有需要的数据,但是当我发送它进行查看时,它没有显示任何内容。通常,通常的方法是使用:
$this->set('products',$products);
但在这里,我用于Ajax请求:
$this->autoRender = false;
所以,这可能是数据没有出现的原因,但是我怎样才能发送数据进行查看? 请帮帮我。
更新 我的观点代码是:
<?php foreach ($products as $product): ?>
<tr>
<td><?php echo $product ['Discount']['product_id']; ?></td>
<td><?php echo $this->Html->link($product['Product']['product_name'], array('controller'=>'products', 'action' => 'view', $product['Discount']['product_id'])); ?></td>
<td>$<?php echo $product ['Order']['benefit']; ?></td>
<td><?php echo $product ['Order']['number']; ?></td>
</td>
</tr>
<?php endforeach; ?>
和我的Ajax脚本:
<script>
$(function(){
$('#btnSubmit').click(function() {
var from = $('#from').val();
var to = $('#to').val();
alert(from+" "+to);
$.ajax({
url: "/project/cakephp/orders/hottest_products",
type: 'POST',
data: {"start_time": from, "end_time": to },
beforeSend: function(xhr){xhr.setRequestHeader('X-Test-Header', 'test-value');},
success: function(data){
console.log(data);
}
});
});
});
答案 0 :(得分:0)
您应该在名为ajax.ctp
具有以下内容:
<?php echo $content_for_layout?>
然后:
if($this->RequestHandler->isAjax()) {
$this->layout = 'ajax';
}
答案 1 :(得分:0)
您应该返回
之类的数据 Debugger::dump($products);
//send data to the view.
return $products;`
建议return json_encode($products);
并在成功方法中解码