2010-08-01 107 views
2

我在想什么是用jQuery处理AJAX调用的最佳方法?现在我正在做类似如下: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调用?

问候, 汤姆

回答

1

你有什么好看在这里,虽然我不认为你需要一个$.parseJSON()那里,它应该已经是在这一点上的对象,这应该工作:

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

作为一个方面说明,从可读性/可维护性的角度来看,我会重命名html说法是data,就像这样:

success: function(data) { 

这是纯粹的偏好设置,但是当它是HTML类型的响应时使用html,或者当它是JSON时,使用data或其他内容,因为您期待的对象可以让外界更容易阅读。

+0

谢谢您的回答尼克。我很高兴听到我正确地做了这件事,花了几个小时阅读jQuery手册。 BTW ...我想知道同样的方式关于一个对象,但是当我尝试'$(“#success”)。html(html.rows [0] .name);'在它不工作之前。想知道为什么? – Tom 2010-08-01 13:27:28

+0

@Tom - 如果你的console.log(html.rows)'你在控制台(Firebug/Chrome)中获得了什么?它仍然是一个字符串或对象? – 2010-08-01 13:30:07

+0

@Nick - 由于未知原因,它是一个字符串。 – Tom 2010-08-01 13:35:30

0

@汤姆 - 你需要的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); 
       } 
      }