jQuery AJAX调用,如何处理

时间:2022-04-13 08:56:53

I'm wondering what is the best method to handle AJAX calls with jQuery? Right now I'm doing something like following:

我想知道用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;
});

In test.php file, I'm checking if request is an AJAX request. If it's an AJAX request I'm running a database query to get some data (this part isn't important in this question, I think):

在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;
}

Now I'm wondering if my method is the best possible? FYI I'm using KohanaPHP framework currently, so I want to not break MVC "rules". If I'm doing it wrong, do you have any tips and suggestions how to handle AJAX calls in controllers?

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

Regards, Tom

问候,汤姆

2 个解决方案

#1


1  

What you have looks good here, though I don't think you need a $.parseJSON() there, it should already be an object at that point, this should work:

你在这里看起来很不错,虽然我不认为你需要一个$ .parseJSON(),它应该已经是一个对象,这应该工作:

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

As a side note, from a readability/maintainability perspective, I'd rename your html argument to be data, like this:

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

success: function(data) {

This is purely preference, but using html when it's an HTML type response, and data or something else when it's JSON/already an object you're expecting keeps things a bit easier to read for outsiders.

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

#2


0  

@tom - you need to encode the PHP array like this:

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

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

echo json_encode($data);

But you might want to change the array structure a little. Since the xhr object has a text status I usually encode an JSON array like this:

但您可能希望稍微更改阵列结构。由于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);

Now you can do some nice things like this:

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

           ,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);
                }
            }

#1


1  

What you have looks good here, though I don't think you need a $.parseJSON() there, it should already be an object at that point, this should work:

你在这里看起来很不错,虽然我不认为你需要一个$ .parseJSON(),它应该已经是一个对象,这应该工作:

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

As a side note, from a readability/maintainability perspective, I'd rename your html argument to be data, like this:

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

success: function(data) {

This is purely preference, but using html when it's an HTML type response, and data or something else when it's JSON/already an object you're expecting keeps things a bit easier to read for outsiders.

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

#2


0  

@tom - you need to encode the PHP array like this:

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

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

echo json_encode($data);

But you might want to change the array structure a little. Since the xhr object has a text status I usually encode an JSON array like this:

但您可能希望稍微更改阵列结构。由于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);

Now you can do some nice things like this:

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

           ,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);
                }
            }