我尝试使用 Joomla 1.5 在 ajax 中获取 json 对象,但没有成功。阅读一些谷歌页面,我遵循了似乎是这样做的方法,但是 firebug 上的 javascript 控制台返回 Error: undefined, Status: parsererror
。
代码如下:
客户端:
$(document).ready(function() {
$.ajax({
url: "http://localhost/courses/2015/ppc/index.php?option=com_exammonitor&task=exchangeExamMonitorData",
data: {
'first_name': "{TOKEN:FIRSTNAME}",
'last_name': "{TOKEN:LASTNAME}",
'exam_name': "{SURVEYNAME}"
},
dataType: "json",
type: "POST",
error: function(xhr, status, errorThrown) {
alert("Ajax error!");
console.log("Error: " + errorThrown);
console.log("Status: " + status);
console.dir(xhr);
},
success: function(data){
console.log(data);
}
})
});
服务器端(controller.php):
function exchangeExamMonitorData()
{
$user =& JFactory::getUser();
//TODO: verificar existência e permissão de usuário
$post = JRequest::get('post');
$firstName = $post['first_name'];
$lastName = $post['last_name'];
$examName = $post['exam_name'];
$model =& $this->getModel('exammonitor');
$result = $model->exchangeExamMonitorData($firstName, $lastName, $examName);
$response = array("success" => true, "result" => $result);
// Get the document object.
$document = JFactory::getDocument();
// Set the MIME type for JSON output.
$document->setMimeEncoding('application/json');
echo json_encode($response);
}
调用de ajax时,显示Error: undefined, Status: parsererror
,并显示错误参数消息。
缺少哪一 block ?
最佳答案
我不知道这是否是最好的答案,可能不是,因为我刚刚开始 Joomla 开发。我发现我必须捕获应用程序才能将请求发送回 ajax 调用,因此在服务器端声明全局变量 $mainframe
解决了问题。
function exchangeExamMonitorData()
{
global $mainframe;
// original code
$mainframe->close();
}
关于javascript - 在 Joomla 1.5 中使用 json_encode 调用从 ajax 获取响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30787719/