问题
Still having problems figuring out how to use Ajax and the Joomla framework together. I've created a Joomla component which I can access with:
index.php?option=com_mycomponent
I'm using Jquery with Ajax in components/com_mycomponent/views/mycomponent/tmpl/default.php
:
<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
?>
<html>
<head>
<title>Ajax with jQuery Example</title>
<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/JavaScript">
$(document).ready(function(){
$("#generate").click(function(){
$("#quote p").load("components/com_mycomponent/views/mycomponent/tmpl/script.php");
});
});
</script>
</head>
<body>
<div id="wrapper">
<div id="quote"><p> </p></div>
<input type="submit" id="generate" value="Generate!">
</div>
</body>
</html>
Then in the script.php file I have this:
<?php
$user =& JFactory::getUser();
echo "This is the user: ".$user;
?>
If I don't put any Joomla framework code in script.php it works fine. But the purpose of doing this is that I need to use the Joomla framework and hence the whole point of creating a component. But I still don't understand how I need to structure the Joomla component so I don't get the Class 'JFactory' not found
error?
回答1:
Didn't end up taking too long in the end. The only file that is required is the default.php, so you can delete the script.php and other odd files you have in there.
Default.php
<?php
defined('_JEXEC') or die('Restricted access');
//$document =& JFactory::getDocument();
//$document->addScript("https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js");
$user =& JFactory::getUser();
?>
<div id="wrapper">
<div id="quote" style="display:none; padding-bottom:10px;">
<?php
echo "<p>This is your username: " . $user->username . "</p>";
echo "<p>This is your realname: " . $user->name . "</p>";
echo "<p>This is your user ID: " . $user->id . "</p>";
?>
</div>
<input type="submit" id="generate" value="Generate!">
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#generate").click(function(){
$("#quote").show();
});
});
</script>
I have commented out the jquery reference in the code, seeing as the widgetkit is already loading a copy of it, but kept it there just incase.
Instead of loading another file, what this does is, it hides #quote
div tag and when the button is clicked, it reveals it with the data inside it. In this one, I have added realname
and user ID
just incase.
Hope this helps.
Regards
回答2:
I think the correct way to do this is to add a task in your controller.php file in the component.
http://docs.joomla.org/Adding_AJAX_to_your_component
来源:https://stackoverflow.com/questions/11752061/joomla-with-ajax-fatal-error-class-jfactory-not-found