简体   繁体   English

ResponseText应该是json_encode,而不是Cakephp中的HTML

[英]ResponseText should be a json_encode, not HTML in cakephp

I am trying to display the number of rows of the table. 我试图显示表的行数。 In the controller, I have a function like: 在控制器中,我有一个类似的功能:

public function index(){
  $count= $moviecount = $this->Media->find('count');
  $this->set(array('data' => $count, '_serialize' => 'data'));
}

In my index.ctp, I have a regular HTML script with divs and everything. 在index.ctp中,我有一个包含div和所有内容的常规HTML脚本。 Here in my JavaScript file, I do something like this. 在我的JavaScript文件中,我做了这样的事情。

function checkTbl(){
checkBrowser();//callback function
xmlhttprequestobject.open("GET", "/url/", false); //async
xmlhttprequestobject.onreadystatechange = function(){
if(xmlhttprequestobject.readyState==4 && xmlhttprequestobject.status==200){
  alert(xmlhttprequestobject.responseText);
}
}
xmlhttprequestobject.send();
}

but when I click the image event onClick, the response is HTML, not the integer value of the count. 但是当我单击图像事件onClick时,响应为HTML,而不是计数的整数。 please help. 请帮忙。

Are you loading the RequestHandler component? 您是否正在加载RequestHandler组件? If you don't call the URL with the .json extension you have to manually set the view to respond as json. 如果不使用扩展名为.json的URL调用,则必须手动将视图设置为以json响应。 If you parse the extensions using the router you'll automatically get a json response if the component is loaded. 如果使用路由器解析扩展,则在加载组件后会自动获得json响应。 Did you follow the instructions on this page ? 您是否遵循此页面上的指示?

If you want resposeText as json_encode then try something like this in your controller function.By using this you'll not need .ctp file. 如果您想将resposeText作为json_encode,请在控制器函数中尝试类似的方法,使用此方法将不需要.ctp文件。

 public function index()
 {
     $count= $moviecount = $this->Media->find('count');
     //$this->set(array('data' => $count, '_serialize' => 'data'));
    return new CakeResponse(array('body' => json_encode($count)));
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM