繁体   English   中英

在Joomla中调用Ajax控制器吗?

[英]Ajax call to controller in Joomla?

好的,我为Joomla安装了一个组件,但现在我正在努力添加自定义计数器视图。

在该组件的controller.php中,我添加了以下功能:

    function updateView() {
    $db = JFactory::getDBO();
    $videoid = JRequest::getVar('videoid');
    if ($videoid) {
        $query = "update #__hdflv_upload SET times_viewed=1+times_viewed where id=$videoid";
        $db->setQuery($query);
        $db->query();
    }
    $query = "select times_viewed from #__hdflv_upload where id=$videoid";
    $db->setQuery($query);
    $timeView = $db->loadResult();
    echo $timeView;
    jexit();
}

无论如何,在页面中,我尝试使用php调用此函数,并且工作正常,但是启用了缓存后,脚本停止工作。 他们对我说,在Joomla中,反对意见应该始终存在于Ajax中。 但是我是Ajax的专家,我尝试过这样做但没有结果:

    <script>
$.ajax({
    url: 'index.php?option=com_contushdvideoshare&task=updateView&format=raw',
    success: function(data){
                if(!data.length){
            // Throw an error
            return;
        }

       $('.container').html(data);

    }
});
</script>

有人可以帮我吗? 谢谢

首先,您的第一个代码中有一个sql注入漏洞,它应该是:

function updateView() {
    $db = JFactory::getDBO();
    $videoid = JRequest::getInt('videoid');
    if ($videoid) {
        echo '0';
        jexit();
    }
    $query = "update #__hdflv_upload SET times_viewed=1+times_viewed where id=".(int)$videoid;
    $db->setQuery($query);
    $db->query();

    $query = "select times_viewed from #__hdflv_upload where id=".(int)$videoid;
    $db->setQuery($query);
    $timeView = $db->loadResult();
    echo $timeView;
    jexit();
}

如果您想获取整数,请使用JRequest :: getInt('videoid'),Joomla将为您检查并验证输入。

您也可以直接在sql查询中将其强制转换为int,这是一个好习惯。

然后,获取查询被缓存。 您有两种解决方案来更改此行为:

  • 发布请求永远不会被缓存,因此请使用ajax发布请求
  • 在ajax函数中指定不应缓存此请求

这是修改后的js代码

$.ajax({
    url: 'index.php?option=com_contushdvideoshare&task=updateView&format=raw',
    method: "POST", //Use post method
    cache: false, //Specify no cache
    success: function(data){
        if(!data.length){
            // Throw an error
           return;
        }
       $('.container').html(data);
    }

暂无
暂无

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

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