我知道还有很多其他重复的'关于这个话题的问题。但我仍然坚持。我只是试图通过ajax来控制从PHP传递的数组。
在CakePHP 2.X中:
在视图中:
<button class="quarter q1" value="1" value>Quarter 1</button>
<button class="quarter q2" value="2">Quarter 2</button>
<button class="quarter q3" value="3">Quarter 3</button>
<button class="quarter q4" value="4">Quarter 4</button>
<script type="text/javascript">
jQuery(document).ready(function($){
$('.quarter').click(function(e){
e.preventDefault();
var quarter_val = this.value;
$.ajax({
url: "/rep/testQueue",
type: "post",
data: {quarter_val:quarter_val},
success: function(data) {
var months = <?php echo json_encode($months); ?>;
console.log(months);
},
error: function(){
},
complete: function() {
}
});
});
});
</script>
在我的控制器中:
public function queue() {
if($this->request->isPost()) {
$this->autoRender = false;
$this->layout = false;
$quarter_chosen = $this->request->data['quarter_val'];
$month s= $this->_get_quarter($quarter_chosen);
$this->set('months', $months);
}
}
public function _get_quarter($quarter_chosen){
switch($quarter_chosen) {
case 1: return array('January', 'February', 'March');
case 2: return array('April', 'May', 'June');
case 3: return array('July', 'August', 'September');
case 4: return array('October', 'November', 'December');
}
}
我尝试过多种不同的事情。 array_map,JSON.parse,将dataType设置为json。不过,当我尝试在ajax成功函数中控制日志月份时,我得到null。
如果我没有正确理解某些内容,请填写我的信息,或者分享相关内容。谢谢你。
答案 0 :(得分:0)
您的ajax请求是:
url: "/rep/testQueue",
并且在你的控制器中你没有任何testQueue()方法。在cakePHP中你的ajax请求网址必须是:
url: "/yourControllerName/yourMedhodName",
答案 1 :(得分:0)
Mate,你可以使用蛋糕的JS助手。关于&#39;成功&#39;在Js-&gt;请求方法中,数据将作为&#34;数据&#34;接收。
//somewhere on view
$this->Js->get('.quarter')->event('click',
'var quarter_val = $(this).val();' .
$this->Js->request(
array('controller' => 'ya controller', 'action' => 'ya action' , 'ya arguments (if needed)'),
array(
'async' => true,
'dataExpression' => true,
'data' => '{quarter_val: quarter_val}',
'method' => 'POST',
'success' => 'console.log(data);' // It should print the returned data into your console
)
)
);
//Now, to print the buffered script by the JS helper:
echo $this->Js->writeBuffer();
//To print it into your script block
$this->append('script');
echo $this->Js->writeBuffer();
$this->end();
您的控制器方法应该回显数组,而不是使用$ this-&gt; set()进行设置。您将使用JS接收数据,因此您必须回显json_encoded数据,以便您的脚本可以使用它。
//On your queue method, instead $this->set('months', $months);
echo json_encode($months);
exit();