简体   繁体   English

在Joomla 1.5中通过json_encode调用从ajax获取响应

[英]Get response from ajax with json_encode call in Joomla 1.5

I'm trying to get json object in ajax using Joomla 1.5 without success. 我正在尝试使用Joomla 1.5在Ajax中获取json对象,但没有成功。 Reading some google pages I followed what appear to be the way to do that, but javascript console on firebug returns Error: undefined, Status: parsererror . 阅读一些谷歌页面,我遵循了似乎是这样做的方法,但是萤火虫上的javascript控制台返回Error: undefined, Status: parsererror

The code follows: 代码如下:

Client side : 客户端

$(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);
        }
    })
});

Server side (controller.php): 服务器端 (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);
}

When de ajax is called, it displays Error: undefined, Status: parsererror , and displays the error parameter message. 调用de ajax时,它显示Error: undefined, Status: parsererror ,并显示错误参数消息。

What piece is missing? 缺少哪一块?

I don't know if it is the best answer, probably not, since I've just started with Joomla development. 我不知道这是否是最佳答案,因为我刚开始进行Joomla开发。 I saw that I have to capture the application to send request back to ajax call, so declaring the global variable $mainframe in server side solved the problem. 我看到我必须捕获应用程序才能将请求发送回ajax调用,因此在服务器端声明全局变量$mainframe解决了该问题。

function exchangeExamMonitorData()
{
    global $mainframe;

    // original code

    $mainframe->close();
}

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

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