我正在开发一个再商业网站,通过Javascript/jQuery从用户那里收集关于二手手机的信息。
我试图弄清楚如何在我的QuotesController中创建一个适当的方法,允许我:( 1)使用jQuery/AJAX 2)使用AJAX "post“调用它,返回报价数据,这样我就可以向用户显示价格
下面是我到目前为止所做的: jQuery函数调用:
var data =
{
device_id: quote['device_id'],
carrier_id: quote['carrier_id'],
condition_id: quote['condition_id'],
size: quote['size']
};
// Pull quote using AJAX
$.ajax({
type: "post",
url: "/c4c/quotes/get_quote",
data: data,
dataType: 'json',
success: function(data, textStatus, jqXHR){
alert('success');
alert(jqXHR.responseText);
$('#quote').html(jqXHR.responseText);
},
error: function(jqXHR, textStatus, errorThrown){
alert('error');
alert(jqXHR.responseText);
$('#quote').html(jqXHR.responseText);
}
});
方法在QuotesController中:
// Gets a quote's price via ajax
public function get_quote(){
$this->layout = 'ajax';
$device_id = $this->request->data['device_id'];
$carrier_id = $this->request->data['carrier_id'];
$condition_id = $this->request->data['condition_id'];
$size = $this->request->data['size'];
// Get quote
$quote = $this->Quote->find('first', array('conditions'=>array('Quote.device_id'=>$device_id,
'Quote.carrier_id'=>$carrier_id,
'Quote.condition_id'=>$condition_id,
'Quote.size'=>$size,
)));
$this->set('quote',$quote);
//$this->render('get_quote');
return json_encode($quote);
}
我一直在犯错误,所以我知道我做的是错误的,但我似乎无法在CakePHP的网站上找到任何答案,也无法通过Google找到任何答案。
任何帮助都将不胜感激!
发布于 2012-09-23 07:34:46
一个快速解决你的情况的方法是:
首先,不要做return json_encode($quote);
-为ajax响应创建一个视图文件。它应该位于:App/View/Quotes/Ajax/get_quote.ctp
。
然后设置响应变量:$this->set('quote', $quote);
您还需要设置一些标头,因为我怀疑您使用的默认ajax布局只是一个空布局。在:App/View/layouts/ajax.ctp
中创建布局文件
您可以使用基本的PHP header()
函数来完成这一任务:
header("Cache-Control: no-store, no-cache, max-age=0, must-revalidate");
header('Content-Type: application/json');
echo $content_for_layout;
缓存控制头在那里,因此ajax数据没有任何缓存。如果您正在使用请求/响应监视工具(您应该这样做),您会注意到现在它直接将响应标识为JSON。在你看来,你可以:
echo json_encode($quote);
基于您所提供的稀缺信息,这应该可以解决您的问题,但是在CakePHP中如何最好地使用json/ajax呢?这里有几个步骤。
RequestHandlerComponent::setContent($name, $type = null)
- 看看这里设置任何您喜欢的标题。注意,应该在控制器的setContent()中调用beforeFilter()。https://stackoverflow.com/questions/12545206
复制相似问题