【问题标题】:How to wrap return type of ajax call in success with function如何用函数成功包装ajax调用的返回类型
【发布时间】:2010-07-29 07:19:50
【问题描述】:

我有一个 Web 服务,它总是从我在服务器端定义的类中带回一个对象。

$.ajax 函数的success 方法中,我总是得到这个对象。在客户端,我想添加几个函数来更快地显示其属性。

有没有办法做到这一点? (JSON 对象会返回,我很担心)

【问题讨论】:

  • 在这个问题中,我要求包装 jquery 响应对象(每个响应都会有)。但是在那个问题(你提到的)中,我要求找到与响应对象具有相同 __type 属性的对象(响应对象可能有很多属性)。但这个问题是一般性问题。我问是因为这个问题比以前更清楚了。

标签: jquery ajax json extension-methods


【解决方案1】:

您可以扩展 javascript 对象并为其添加方法:

var json = { name: 'john' };
json.print = function() {
    alert('my name is ' + this.name);
};
json.print();

【讨论】:

    【解决方案2】:

    正如你在上一个关于这个主题的问题中已经告诉我的那样

    how can i add a function to json object which has __type attribute?

    你想拥有一个全局功能。由于您仍然无法将function 添加到json 中,因此您应该声明global function,例如:

    var props = (function(){
       var spacing = '';
    
       function props(json, deep) {
          if(typeof json === 'object'){
             for(var prop in json){
                 if(typeof json[prop] === 'object'){             
                    spacing += '   ';
                    props(json[prop], true); 
                 }
                 else{                
                   console.log(spacing, prop, ': ', json[prop]);
                 }
             }
          }
       }
    
       return props;
    }());
    

    【讨论】:

    • 感谢您的帮助(真的),但在这个问题中,我不是在寻找响应对象的内部属性。只是想为每个响应添加几个功能。顺便说一句,这个答案比stackoverflow.com/questions/3358811/…的答案更好
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多