从函数返回两个或多个值

时间:2021-04-10 09:56:22

I need to return multiple values from a ColdFusion function in an ajax callback function. Here's what I've got:

我需要在ajax回调函数中从ColdFusion函数返回多个值。这就是我有:

$('input[name="StateName"]').live('change', function() {
    var StateID = $(this).parents('tr').attr('id');
    var StateName = $(this).val();
    $.ajax({
        url: 'Remote/State.cfc'
        ,type: "POST"
        ,data: {
            'method': 'UpdateStateName'
            ,'StateID': StateID
            ,'StateName': StateName
        }
        ,success: function(result){
            if (isNaN(result)) {
                $('#msg').text(result).addClass('err');
            } else {
                $('#' + result + ' input[name="StateName"]').addClass('changed');
            };
        }
        ,error: function(msg){
            $('#msg').text('Connection error').addClass('err');
        }
    });
});

If I trap a database error, then the success callback is fired, and the result is Not a Number (It is in fact, the text of the error message). I need the function to also pass back other values. One might be the primary key of the row that caused the error. Another might be the old StateName, so that I can refresh the old value on the screen so that the client will know absolutely for sure that their change did not take effect.

如果我捕获了一个数据库错误,那么将触发成功回调,结果不是一个数字(实际上是错误消息的文本)。我需要这个函数来传递其他值。一个可能是导致错误的行的主键。另一个可能是旧的StateName,这样我就可以刷新屏幕上的旧值,这样客户就可以确信他们的更改不会生效。

I guess I'm breaking the rule of atomicity here and need to fix that, because I'm using result as both the primary key of the row that was updated, or it's the error message if the update fails. I need to return both the primary key and the error message.

我想我打破了原子性的规则,需要修正它,因为我使用result作为被更新的行的主键,或者是更新失败时的错误消息。我需要返回主键和错误消息。

3 个解决方案

#1


6  

Your remote function could return a **JSON string**, containing an object, I suppose.

我想,您的远程函数可以返回一个**JSON字符串**,其中包含一个对象。

It would allow you to have several values inside a single "value".

它允许您在一个“值”中包含多个值。

And JSON being Javascript Object Notation, it's quite easy to read it in Javascript -- and there are libraries to serialize data to JSON in lots of languages.

JSON是Javascript对象表示法,很容易在Javascript中读取——有很多库可以用多种语言将数据序列化为JSON。


For example, here's a JSON string :

例如,这里有一个JSON字符串:

{"status":1,"message":"this is a message","data":{"test":"plop","hello":"world"}}

This corresponds to an object with 3 properties :

这对应于具有3个属性的对象:

  • status
  • 状态
  • message
  • 消息
  • and data ; which is itself another object, that contains two properties.
  • 和数据;它本身是另一个对象,包含两个属性。

Returning this kind of string from your AJax call should not be too hard -- and that's a pretty flexible, and really prowerful, system.

从AJax调用中返回这种字符串应该不会太困难——这是一个非常灵活的、非常有用的系统。

#2


4  

I make all my ajax requests return the same object type. The pattern I use is a pretty common one - my response object always consists of a Success flag, a Data property, and an Errors collection.

我让所有的ajax请求返回相同的对象类型。我使用的模式是一个非常常见的模式——我的响应对象总是由一个成功标志、一个数据属性和一个错误集合组成。

If you jsonify an object like that and return it for all your ajax requests, you can always determine if the request was successful, what the errors were (if any), and if it was successful, you'll have the resulting data. In this way, you'll always be able to handle your responses in a consistent manner.

如果您对这样的对象进行jsonify,并为所有ajax请求返回它,您总是可以确定请求是否成功,错误是什么(如果有),如果成功,您将得到结果数据。通过这种方式,您将始终能够以一致的方式处理您的响应。

Note that the Errors collection would be business logic errors - actual server errors would still trigger the jQuery failure handler. But using the above object, your "success" function looks more like:

注意,错误集合将是业务逻辑错误——实际的服务器错误仍然会触发jQuery失败处理程序。但是使用上面的对象,您的“成功”函数看起来更像:

 if (!result.Success) {
    $('#msg').text(result.Errors[0]).addClass('err');
 } else {
    $('#' + result.Data + ' input[name="StateName"]').addClass('changed');
 };

#3


1  

You can return xml string and then access it in success function:

您可以返回xml字符串,然后在success函数中访问它:

success:function(data)
{
  var err_code,err_msg;
  //read err_code and err_msg:
  // we need 2 different handlers for IE and all other browsers.
            if (! $.browser.msie) 
            {
                // this code surprisingly doesn't work with IE.
                err_code = $('error_code:first',data).text();
                err_msg = $('error_message:first',data).text();
            }
            else
            {
                var xml = new ActiveXObject("Microsoft.XMLDOM");
                xml.async = false;
                xml.loadXML(data);
                err_code = xml.documentElement.getElementsByTagName('error_code')[0].text;                    
                err_msg = xml.documentElement.getElementsByTagName('error_message')[0].text;
            }

}

#1


6  

Your remote function could return a **JSON string**, containing an object, I suppose.

我想,您的远程函数可以返回一个**JSON字符串**,其中包含一个对象。

It would allow you to have several values inside a single "value".

它允许您在一个“值”中包含多个值。

And JSON being Javascript Object Notation, it's quite easy to read it in Javascript -- and there are libraries to serialize data to JSON in lots of languages.

JSON是Javascript对象表示法,很容易在Javascript中读取——有很多库可以用多种语言将数据序列化为JSON。


For example, here's a JSON string :

例如,这里有一个JSON字符串:

{"status":1,"message":"this is a message","data":{"test":"plop","hello":"world"}}

This corresponds to an object with 3 properties :

这对应于具有3个属性的对象:

  • status
  • 状态
  • message
  • 消息
  • and data ; which is itself another object, that contains two properties.
  • 和数据;它本身是另一个对象,包含两个属性。

Returning this kind of string from your AJax call should not be too hard -- and that's a pretty flexible, and really prowerful, system.

从AJax调用中返回这种字符串应该不会太困难——这是一个非常灵活的、非常有用的系统。

#2


4  

I make all my ajax requests return the same object type. The pattern I use is a pretty common one - my response object always consists of a Success flag, a Data property, and an Errors collection.

我让所有的ajax请求返回相同的对象类型。我使用的模式是一个非常常见的模式——我的响应对象总是由一个成功标志、一个数据属性和一个错误集合组成。

If you jsonify an object like that and return it for all your ajax requests, you can always determine if the request was successful, what the errors were (if any), and if it was successful, you'll have the resulting data. In this way, you'll always be able to handle your responses in a consistent manner.

如果您对这样的对象进行jsonify,并为所有ajax请求返回它,您总是可以确定请求是否成功,错误是什么(如果有),如果成功,您将得到结果数据。通过这种方式,您将始终能够以一致的方式处理您的响应。

Note that the Errors collection would be business logic errors - actual server errors would still trigger the jQuery failure handler. But using the above object, your "success" function looks more like:

注意,错误集合将是业务逻辑错误——实际的服务器错误仍然会触发jQuery失败处理程序。但是使用上面的对象,您的“成功”函数看起来更像:

 if (!result.Success) {
    $('#msg').text(result.Errors[0]).addClass('err');
 } else {
    $('#' + result.Data + ' input[name="StateName"]').addClass('changed');
 };

#3


1  

You can return xml string and then access it in success function:

您可以返回xml字符串,然后在success函数中访问它:

success:function(data)
{
  var err_code,err_msg;
  //read err_code and err_msg:
  // we need 2 different handlers for IE and all other browsers.
            if (! $.browser.msie) 
            {
                // this code surprisingly doesn't work with IE.
                err_code = $('error_code:first',data).text();
                err_msg = $('error_message:first',data).text();
            }
            else
            {
                var xml = new ActiveXObject("Microsoft.XMLDOM");
                xml.async = false;
                xml.loadXML(data);
                err_code = xml.documentElement.getElementsByTagName('error_code')[0].text;                    
                err_msg = xml.documentElement.getElementsByTagName('error_message')[0].text;
            }

}