jQuery AJAX调用,如何处理

时间:2010-08-01 13:21:07

标签: ajax jquery kohana

我想知道用jQuery处理AJAX调用的最佳方法是什么?现在我正在做以下事情:

$("#test").live('click', function(){
    // Process form
    $.ajax({
        type: "post",
        url: "test.php",
        success: function(html){
            if(html.success == 0) {
                alert('Error');
            } else {
                var obj = $.parseJSON(html.rows);
                $("#success").html(obj[0].name);
            }
        },
        dataType:'json'
    }); 
    return false;
});

在test.php文件中,我正在检查请求是否是一个AJAX请求。如果这是一个AJAX请求,我正在运行数据库查询来获取一些数据(这个部分在这个问题中并不重要,我认为):

// query goes here
if(mysql_num_rows($query) > 0 ) {
    $result['success'] = 1;
    $result['data'] = json_encode($data);
} else {
    $result['success'] = 0;
}

现在我想知道我的方法是否最好?仅供参考我目前正在使用KohanaPHP框架,所以我想不要打破MVC“规则”。如果我做错了,您是否有任何提示和建议如何在控制器中处理AJAX调用?

此致 汤姆

2 个答案:

答案 0 :(得分:1)

你在这里看起来很不错,虽然我觉得你不需要$.parseJSON(),但那时它应该已经是一个对象了,这应该有效:

$("#success").html(html.rows[0].name);

作为旁注,从可读性/可维护性的角度来看,我将html参数重命名为data,如下所示:

success: function(data) {

这纯粹是首选,但是当它是HTML类型响应时使用html,而当它是JSON /已经是您期望的对象时使用data或其他东西会让事情更容易阅读外人。

答案 1 :(得分:0)

@tom - 您需要像这样对PHP数组进行编码:

$data = array(
    'status' => 'success'
);

echo json_encode($data);

但是你可能想稍微更改数组结构。由于xhr对象具有文本状态,因此我通常编码JSON数组,如下所示:

$response = array(
    'status' => 'success' // or flash or error
    ,'flash' => array(
                   'header' => 'whatever is wrong with submission of data html list format'
                   'fields' => array('field names to be highlighted')
                   )

    ,'html'  => 'html presentation'
    ,'data   => array('json data')
);

echo json_encode($response);

现在你可以做一些像这样的好事:

           ,success:    function(response) {
                if (response.status === 'success') {
                    $('.basic_container').hide();
                    that.removeDataTable();
                    that.getContent(contentUrl);
                    $('.basic_container').show();
                }
                if (response.status === 'flash') {
                    $('#flash').html(response.flash.header);
                    $('#flash').show();
                    that.highlightWithFlash(response.flash.fields);
                }
            }
相关问题