jquery ajax returns doc type and a bunch of other things I don't want
I am trying to get some data through ajax and I for whatever reason, I am getting the doctype, the title, meta data... and the data I want. All I want is the JSON data. I am using joomla 1.5
My jQuery:
jQuery(document).ready(
function() {
jQuery('#catagoryChange').click(
function (event) {
event.preventDefault();
jQuery.getJSON("index.php?option=com_test&task=aJax&tmpl=component")
.success(function(data) {alert(data.myName); })
.error(functio开发者_JAVA技巧n(data) {alert("error"); });
} // end of function event
); // end of click
} // end of function
); // end of document.ready
my function that is suppose to echo only the json:
function testAxaj() {
$json = '
{
"myName": "Testing"
}
';
header('Content-type: application/json');
echo $json;
}
And this is what it returns
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-gb" lang="en-gb" dir="ltr" >
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="robots" content="index, follow" />
<meta name="keywords" content="joomla, Joomla" />
<meta name="description" content="Joomla! - the dynamic portal engine and content management system" />
<meta name="generator" content="Joomla! 1.5 - Open Source Content Management" />
<title>Administration</title>
<link href="/Test/administrator/templates/khepri/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<script type="text/javascript" src="/Test/includes/js/joomla.javascript.js"></script>
<script type="text/javascript" src="/Test/media/system/js/mootools.js"></script>
<link href="templates/khepri/css/general.css" rel="stylesheet" type="text/css" />
<link href="templates/khepri/css/component.css" rel="stylesheet" type="text/css" />
</head>
<body class="contentpane">
{
"myName": "Testing"
}
</body>
</html>
That looks more like a Joomla issue to me. You will need to configure it not display the HTML template at all.
try changing the php function to:
function testAxaj() {
$json = array("myName" => "Testing");
header('Content-type: application/json');
echo json_encode($json);
}
I figured it out! I needed to use the php exit function after the echo:
function testAxaj() {
$json = '
{
"myName": "Testing"
}
';
header('Content-type: application/json');
echo $json;
exit;
}
Works perfect now! :-)
精彩评论