CodeIgniter / jQuery – Ajax调用返回完整的html页面而不是我的echo

在我看来,我有一个ajax调用:

$(".previous").click(function() { $.ajax({ type: "POST", url: "planner/get_cal", data: {current_month: current_month}, success: function(msg){ alert(msg); } }); 

我的Planner控制器中的get_cal函数:

 function get_cal() { echo "dinosaurs"; } 

但是,它不返回“恐龙”,而是返回完整的HTML页面。 我无法弄清楚为什么。 思考? 非常感谢。

我通过使用我的问题的评论中建议的前导斜杠来解决这个问题。

 $.ajax({ type: "POST", url: "/planner/get_cal", dataType: "text", data: {current_month: current_month}, success: function(msg){ alert(msg); } }); 

您也可以通过在php文件中添加echo之后的exit来获取它,如下所示:

 function get_cal() { echo "dinosaurs";exit; } 

它会工作。 🙂

尝试将dataType设置为“text”

 $.ajax({ type: "POST", url: "planner/get_cal", data: {current_month: current_month}, dataType: "text", success: function(msg){ alert(msg); } }); 

当使用Controler / Method uri段的CodeIgniter结构时,我发现在jquery ajax请求中使用../../controller/method作为我的URL更容易。 我还建议指定一个dataType,以便解析该字符串并将其作为对象返回。

这是一个例子;

 $.ajax({ type: "POST", dataType: "json", url: "../../controller/method", success: mySuccessFunction }); 

当您的php文件和html文件不在正确的路径上时,这些类型的问题就会出现,以便apache服务器可以解析php文件。 没有提到类型:’text’和任何其他格式,ajax也可以。 但请确保您的服务器已达到php文件。 否则整个文件将被视为文本并返回。

对于任何使用Zend Framework的人来说,我遇到的问题是AJAX响应返回完整的HTML而不是json_encode()响应。 通过将以下内容添加到我的控制器来解决此问题:

  if ($this->getRequest()->isXmlHttpRequest()) { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); } 

只是想提一下:url真的取决于你如何设置.htaccess和文件夹结构。 所以最好的方法是尝试几个url,即:
../../controller/method
../controller/method
server_folder / index.php的/控制器/方法
http://example.com/server_folder/index.php/controller/method
然后选择在特定情况下效果最佳的那个。