gpt4 book ai didi

php - CakePHP - 使用 php 变量加载 View 并在 ajax 中返回

转载 作者:搜寻专家 更新时间:2023-10-31 21:27:49 25 4
gpt4 key购买 nike

好吧,这几天让我发疯了。

我有一个表格:

echo $this->Form->create(FALSE, array('id' => 'AdminGeneralReport', 'class' => 'ReportForm'));
echo '<div class="row">';
echo $this->Form->input('ReportCenter', array(
'type'=>'select', 'div' => 'form-group',
'options' => $centers,
'label' => 'المركز',
'class' => 'form-control report-center',
'selected' => isset($selections['CenterID'])? $selections['CenterID']['value'] : 'default'
));

echo $this->Form->input('ReportYears', array(
'type'=>'select', 'div' => 'form-group',
'options' => $years,
'label' => 'العام الدراسي',
'class' => 'form-control report-year',
'selected' => isset($selections['YearID'])? $selections['YearID']['value'] : 'default'
));
echo $this->Form->end();

提交 jQuery:

$('.ReportForm').off('submit').on('submit', function(e){
e.preventDefault();
var formID = $(this).attr('id');
var data = JSON.stringify($(this).serializeObject());
var url = base_url + "Reports/" + formID;
var targetSelector = $(this).attr('data-target') || '.results-row';
var $target = $(targetSelector);

// Show app loading
$('#AppLoading').show();

$.ajax({
url : url,
type : 'POST',
ContentType : 'application/json',
data : {'data': data}
}).done(function(response){
try{
response = JSON.parse($response);
if(response.status == 'success'){
$target.html(response.html);
}
else{
$('#AppWell').show('slow').children('p').html(response.msg);
}
}
catch (ex) {
var msg = 'عذراً، حدث خطأ في إنشاء التقرير. برجاء المحاولة لاحقاً';
$('#AppWell').show('slow').children('p').html(msg);
console.log('Exception :: ' + ex.toString());
console.log('Response :: ' + response);
}
}).fail(function(request, status, error){
var msg = 'عذراً، حدث خطأ في إنشاء التقرير. برجاء المحاولة لاحقاً';
$('#AppWell').show('slow').children('p').html(msg);
console.log('XXXXX Ajax Failure :: ' + error);
}).always(function(){
// Hide app loading
$('#AppLoading').hide();
});
});

问题/需求:我想加载另一个 View 并使用 json 或任何可能的方式将其附加到此表单之后。


这是我要加载的 View 的一部分:

<?php if(isset($selections['Filtered']) && $selections['Filtered'] == TRUE ){
echo '<div class="row">';
$Report = '';
if(isset($selections['SexID']) && $selections['SexID']['value'] != 'default'){
$Report .= '<div class="report-info">
<p class="title">الجنس</p>
<p class="value">'.$selections['SexID']['text'].'</p>
</div>';
}
if(isset($selections['GovID']) && $selections['GovID']['value'] != 'default'){
$Report .= '<div class="report-info">
<p class="title">المحافظة</p>
<p class="value">'.$selections['GovID']['text'].'</p>
</div>';
}

echo '</div>';
?>
<div class="cur-report custom-inverse">
<?=$Report;?>
</div>

这是 PHP 代码的一部分:

// This is the function the ajax calls
public function AdminGeneralReport()
{
// Enable automatic view class switching on content types
public $components = array('RequestHandler');

// Disable auto rendering
$this->autoRender = false;
// Create new view to return to ajax request
$view = new View($this, false);

// Define selections array
$selections = array();

// Get AJAX data
$postData = $this->request->data;
// Decode post data to JSON object
$data = json_decode($postData);

// Create response object
$response = new stdClass();
$response->status = 'fail'; // Should be changed by success scenario

// ********* Center Condition ********* //
$centerCond = '';
// Check if Center is set
if($data->ReportCenter != 'default'){
$centerID = $data->ReportCenter;
$selections['CenterID']['value'] = $centerID;
$selections['CenterID']['text'] = $centers[$centerID];
$selections['Filtered'] = TRUE;

$centerCond = array('CenterID' => $centerID);
}
// *********************************************** //

// ********* Year Condition ********* //
$yearCond = '';
// Check if Academic Year is set
if($data->ReportYears != 'default'){
$yearID = $data->ReportYears;
$selections['YearID']['value'] = $yearID;
$selections['YearID']['text'] = $years[$yearID];
$selections['Filtered'] = TRUE;

$yearCond = array('YearID' => $yearID);

$allTerms = $this->Term->find('all', array('conditions' => array('YearID' => $yearID),
'fields' => array('ID', 'TermName')));
// Convert results from 3D array to 1D array
for($i = 0; $i < count($allTerms); $i++){
$terms[$allTerms[$i]['Term']['ID']] = $allTerms[$i]['Term']['TermName'];
}
$terms['default'] = 'الكل';
}
// *********************************************** //

if($selections){
$response->status = 'success';
}
else{
$response->msg = 'لا توجد بيانات لهذه الإختيارات';
}

$view->set(compact('results','selections'));
$view->set('_serialize', array('results', 'selections'));
$html = $view->render('Admin/General', FALSE);
$response->html = $html;

echo json_encode($response);
die();
}

注意:我在 Config/router.php 中配置了这个

/**
* Enable extensions routing for data views
*/
Router::parseExtensions('json');

最佳答案

终于解决了!!!

我试图使它成为一个数据 View json/xml 而让我自己感到困惑......而我需要做的就是格式化返回的 View :

返回的 View 有很多"\r\n\'\""...都是jQuery代码中JSON解析失败的转义序列。

而且我不必包含 Router::parseExtensions('json'); 以及 public $components = array('RequestHandler');


这是 PHP 代码:

$results = array();     // Fill it
$selections = array(); // Fill it
...
// Disable auto rendering
$this->autoRender = false;
// Create new view to return to ajax request
$view = new View($this, false);
$view->set(compact('results','selections'));
$view->set('_serialize', array('results', 'selections'));

$html = stripcslashes( stripslashes( $view->render('Admin/General', FALSE) ) );
$response->html = $html;

echo json_encode($response);
die();

注意:stripcslashes() 删除“\r\n”转义序列,而stripslashes 将删除“\'\”转义序列


jQuery 代码:

$.ajax({
url : url,
type : 'POST',
ContentType : 'application/json',
data : {'data': data}
}).done(function(response){
try{
response = JSON.parse(response);
if(response.status == 'success'){
$target.html(response.html);
}
else{
// ERROR HANDLING
}
}
catch (ex) {
// ERROR HANDLING
console.log('Exception :: ' + ex.toString());
console.log('Response :: ' + response);
}
}).fail(function(request, status, error){
// ERROR HANDLING
console.log('XXXXX Ajax Failure :: ' + error);
}).always(function(){
// Hide loading
});

关于php - CakePHP - 使用 php 变量加载 View 并在 ajax 中返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33692492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com