使用Jquery Ajax获取Joomla user_id

我在Joomla网站上有以下PHP脚本file.php:

$user = JFactory::getUser(); $usr_id = $user->get('id'); 

如果我直接运行它,在HTML中使用:

 include_once "file.php"; 

它会获得用户ID,没问题。

但是,如果通过Ajax请求运行它:

 $.ajax({ url: "other.php", ... 

其他other.php是:

 include_once "file.php"; 

我收到错误:

 Fatal error: Class 'JFactory' not found in file.php on line 3 

为什么? 任何帮助!?

您需要导入Joomla库才能使用JFactory类。 要导入库,请将以下内容添加到文件顶部:

 define( '_JEXEC', 1 ); define( 'JPATH_BASE', dirname(__FILE__) ).'/../..' ); require_once ( JPATH_BASE .'/includes/defines.php' ); require_once ( JPATH_BASE .'/includes/framework.php' ); require_once ( JPATH_BASE .'/libraries/joomla/factory.php' ); $mainframe = JFactory::getApplication('site'); $mainframe->initialise();