Cakephp :获取 Ajax 变量的麻烦



我计划在我的 cakephp 应用程序中使用 Ajax 来更新所选更改的内容,但是,现在我只想返回一个字符串,遗憾的是我无法让它工作,

这是看看我的代码

视图:

//triggered on a select change
$.ajax({
type: 'get',
url: '<?php echo Router::url(array('controller' => 'pages', 'action' => 'getPrices')); ?>',
beforeSend: function(xhr)
{
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
},
success: function(response)
{
console.log(response);//returns the empty echo from get_prices.ctp
console.log(response.testdata);//returns undefined
},  
error: function(e)
{
console.log(e);
}   
}); 

控制器:

public function getPrices()
{
//$this->request->onlyAllow('ajax'); //tried with and without this
$testdata = 'testvalue';

echo json_encode($testdata);
//also tried : $this->set(compact('testdata'));
}

get_prices.ctp:

<?php
if(!empty($testdata))
{
echo $testdata;
}
else
{
echo "empty";
}

console.log(response);在 get_prices.ctp 中从我的回声输出"空">

console.log(response.testdata);输出"未定义"。

我的浏览器的网络选项卡必须说什么:

General
Request URL: http://localhost:8888/myapp/pages/getPrices
Request Method: GET
Status Code: 200 OK
Remote Address: [::1]:8888
Referrer Policy: no-referrer-when-downgrade
Response
empty

返回编码数组

echo json_encode(['testdata'=>$testdata]);

好的,终于让它工作了,

首先,我必须编辑我的路线.php,虽然我确实在那里声明了我的 getPrices 操作,但它与这一行冲突

Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display'));

getPrices 是在之后声明的,因此被忽略了,所以我只是在这行之前声明了它。

然后更新了我的控制器:

public function getPrices()
{
$this->autoRender = false;
$testdata = 'testvalue';
echo json_encode(['testdata'=>$testdata]);
}

在我看来,阿贾克斯:

$.ajax({
url: '<?php echo $this->Html->url(array('controller' => 'pages', 'action' => 'getPrices')); ?>',
datatype: 'json',
cache: false,
data: {myVar:'Success'},
success: function (data) {
console.log('success');
var decodeddata = JSON.parse(data);
console.log(decodeddata.testdata);
},
error: function(){console.log('failed');}
});

它有效。 如果没有这里人们的贡献,我不会这样做,谢谢。

最新更新