我正在使用CakePHP框架。我的问题是,当我打印一个PHP函数时,它给了我一个有很多成员的数组,但是当使用与Ajax相同的函数时,响应是空的。PHP函数返回是一个使用Ajax的空数组,否则不是
Ajax响应函数:
public function functionOne(){
$this->autoRender = false;
if ($this->request->is('ajax')) {
if(!$this->request->data['amount']) {
$json['errors'][] = 'Fill in all the required fields';
}elseif(!is_numeric($this->request->data['amount'])){
$json['errors'][] = 'Field amound has to be a number';
}
if(!$this->request->data['currency_from']){
$json['errors'][] = 'Fill in all the required fields';
}
if(!$this->request->data['currency_to']){
$json['errors'][] = 'Fill in all the required fields';
}
if(!$this->request->data['rate_date']){
$json['errors'][] = 'Fill in all the required fields';
}
if(isset($json['errors'])){
$json['status'] = 'error';
}else{
$json['status'] = 'success';
$json['curs'] = $this->functionTwo($this->request->data['date1']);
$json['rates'] = $this->functionThree($this->request->data['date'], $this->request->data['from'], $this->request->data['to'], $this->request->data['amount']);
}
print_r(json_encode($json));
}
}
查看文件AJAX请求:
$(document).ready(function(){
$('#converter').on('submit', function(e) {
var form = $(this);
e.preventDefault();
$.ajax({
url: '<?php echo $this->Html->url(array(
"controller" => "cur",
"action" => "functionOne"
));
?>',
data: form.serialize(),
type: 'post',
async: true,
success: function (data) {
var json = data;
if (json.status == 'error') {
$('#errors').show();
$('#currencies').hide();
$('#errors').html('');
$.each(json.errors, function (k, v) {
$('#errors').append("<span>" + v + "</span>");
});
}
if (json.status == 'success') {
var json = data;
$('#errors').hide();
$('#currencies').show();
}
}
});
})
});
getCur方法返回格式 “代码”=> “名” 的数组。它从阅读不同来源的XML文件中获取货币。当我在响应外打印函数时,它给了我一个正确的结果,但是使用ajax它只是给了我一个空的数组。
虽然有错误发生。
谢谢!
ajax请求是否成功?检查网络标签(铬) –
你试过'echo $ json'? – rafat
@NorlihazmeyGhazali是的,我获得成功。当状态等于“成功”响应是{“状态”:“成功”,“货币”:[],“currencyRates”:[]},如果状态等于“错误”,那么它给我json充满了错误 – FickDace