不要退出或死亡,Joomla!有它处理这些东西的好方法。
以下答案在 Joomla 中进行了测试!2.5 和 3(对于 1.5。也可以工作)。
一般的
您的任务URL需要如下所示:
index.php?option=com_similar&task=abc&format=raw
然后创建将使用视图的控制器,比如说 Abc,它将包含文件 view.raw.html(与普通视图文件相同)。
下面是生成原始 HTML 响应的代码:
/控制器.php
public function abc()
{
// Set view
JRequest::setVar('view', 'Abc');
parent::display();
}
/views/abc/view.raw.php
<?php
defined('_JEXEC') or die;
jimport('joomla.application.component.view');
class SimilarViewAbc extends JView
{
function display($tpl = null)
{
parent::display($tpl);
}
}
/views/abc/tmpl/default.php
<?php
echo "Hello World from /views/abc/tmpl/default.php";
Note: This is the solution I would use if I had to return HTML (it's cleaner and follows Joomla logic). For returning simple JSON data, see below how to put everything in the controller.
If you make your Ajax request to a subcontroller, like:
index.php?option=com_similar&controller=abc&format=raw
Than your subcontroller name (for the raw view) needs to be abc.raw.php
.
This means also that you will / may have 2 subcontrollers named Abc.
If you return JSON, it may make sense to use format=json
and abc.json.php
. In Joomla 2.5. I had some issues getting this option to work (somehow the output was corrupted), so I used raw.
If you need to generate a valid JSON response, check out the docs page Generating JSON output
// We assume that the whatver you do was a success.
$response = array("success" => true);
// You can also return something like:
$response = array("success" => false, "error"=> "Could not find ...");
// Get the document object.
$document = JFactory::getDocument();
// Set the MIME type for JSON output.
$document->setMimeEncoding('application/json');
// Change the suggested filename.
JResponse::setHeader('Content-Disposition','attachment;filename="result.json"');
echo json_encode($response);
You would generally put this code in the controller (you will call a model which will return the data you encode - a very common scenario). If you need to take it further, you can also create a JSON view (view.json.php), similar with the raw example.
Security
Now that the Ajax request is working, don't close the page yet. Read below.
Don't forget to check for request forgeries. JSession::checkToken()
come in handy here. Read the documentation on How to add CSRF anti-spoofing to forms
Multilingual sites
It may happen that if you don't send the language name in the request, Joomla won't translate the language strings you want.
Consider appending somehow the lang param to your request (like &lang=de
).
New in Joomla 3.2! - Joomla! Ajax Interface
Joomla 现在提供了一种轻量级的方式来处理插件或模块中的 Ajax 请求。您可能想使用 Joomla!如果您还没有组件或者需要从已有的模块发出请求,则为 Ajax 接口。