如何在 Joomla 组件中发出 Ajax 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13478108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 10:52:30  来源:igfitidea点击:

How to make an Ajax request in Joomla Component

ajaxjoomla

提问by Jonuux

This a screen shot of what I get when I call my ajax request:

这是我调用 ajax 请求时得到的屏幕截图:

enter image description here

在此处输入图片说明

How do I run only the task, without printing the whole page? This is my ajax call:

如何只运行任务而不打印整个页面?这是我的ajax调用:

$.ajax
({
type: "POST",
url: "index.php?option=com_similar&task=abc",
    data: {
        id: id,
        name: name,
        similar_id: similar_id,
    },
cache: false,
success: function(html)
{
$("#flash").fadeOut("slow");
$("#content"+similar_id).html(html);
} 
});
});

$(".close").click(function()
{
$("#votebox").slideUp("slow");
});

});

回答by Valentin Despa

Don't go with exit or die, Joomla! has it's nice way of dealing with this stuff.

不要退出或死亡,Joomla!有处理这些东西的好方法。

The answers below are tested in Joomla! 2.5 & 3 (for 1.5. may work as well).

以下答案已在 Joomla 中进行测试!2.5 & 3(对于 1.5. 也可以)。



General

一般的

Your URLfor the task needs to look like this:

您的任务URL需要如下所示:

index.php?option=com_similar&task=abc&format=raw

index.php?option=com_similar&task=abc&format=raw

You than create the controller which will use the view, let's say Abc, which will contain the file view.raw.html (identical to a normal view file).

您然后创建将使用视图的控制器,比如说 Abc,它将包含文件 view.raw.html(与普通视图文件相同)。

Below you have the code for generate a raw HTML response:

下面是生成原始 HTML 响应的代码:

/controller.php

/控制器.php

public function abc() 
{
    // Set view
    JRequest::setVar('view', 'Abc');
    parent::display();
}

/views/abc/view.raw.php

/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

/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.

注意:如果我必须返回 HTML,这是我会使用的解决方案(它更干净并遵循 Joomla 逻辑)。要返回简单的 JSON 数据,请参阅下文如何将所有内容放入控制器中。



If you make your Ajax request to a subcontroller, like:

如果您向subcontroller发出 Ajax 请求,例如:

index.php?option=com_similar&controller=abc&format=raw

index.php?option=com_similar&controller=abc&format=raw

Than your subcontroller name (for the raw view) needs to be abc.raw.php.

比您的子控制器名称(对于原始视图)需要为abc.raw.php.

This means also that you will / may have 2 subcontrollers named Abc.

这也意味着您将/可能有 2 个名为 Abc 的子控制器。

If you return JSON, it may make sense to use format=jsonand 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.

如果您返回 JSON,则使用format=jsonand可能是有意义的abc.json.php。在 Joomla 2.5 中。我在使用此选项时遇到了一些问题(不知何故输出已损坏),所以我使用了 raw。



If you need to generate a valid JSON response, check out the docs page Generating JSON output

如果您需要生成有效的 JSON 响应,请查看文档页面生成 JSON 输出

// 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.

您通常会将此代码放在控制器中(您将调用一个模型,该模型将返回您编码的数据——这是一个非常常见的场景)。如果您需要更进一步,您还可以创建一个 JSON 视图 (view.json.php),类似于原始示例。



Security

安全

Now that the Ajax request is working, don't close the page yet. Read below.

现在 Ajax 请求正在工作,现在不要关闭页面。参见下文。

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

不要忘记检查请求是否伪造。JSession::checkToken()在这里派上用场。阅读有关如何向表单添加CSRF 反欺骗的文档



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.

可能会发生这样的情况,如果您不在请求中发送语言名称,Joomla 将不会翻译您想要的语言字符串。

Consider appending somehow the lang param to your request (like &lang=de).

考虑以某种方式将 lang 参数附加到您的请求中(如&lang=de)。



New in Joomla 3.2!- Joomla! Ajax Interface

Joomla 3.2 的新功能!-乔姆拉!Ajax 接口

Joomla now provides a lightweight way to handle Ajax request in a plugin or module. You may want to use the Joomla! Ajax Interface if you don't have already a component or if you need to make requests from a module your already have.

Joomla 现在提供了一种轻量级的方式来处理插件或模块中的 Ajax 请求。您可能想使用 Joomla! 如果您还没有组件或者需要从已有的模块发出请求,请使用 Ajax 接口。

回答by elk

If you just want to include the response output in some HTML element, append format=raw to your URL as mentioned above. Then you could have a controller function like this:

如果您只想在某些 HTML 元素中包含响应输出,请按照上述方法将 format=raw 附加到您的 URL。然后你可以有一个这样的控制器功能:

function abc(){

//... handle the request, read variables, whatever
print "this is what I want to place in my html";

}

The AJAX response will output everything you printed / echoed in the controller.

AJAX 响应将输出您在控制器中打印/回显的所有内容。