常见的JSON调用类

时间:2011-06-09 07:46:33

标签: javascript json

var JsonClientPatientSearch = Titanium.Network.createHTTPClient();

    // API Url to call
    var url = GetAPIUrl() + "PatientSearch";
    JsonClientPatientSearch.open("POST", url);
    //setting Request Header
    JsonClientPatientSearch.setRequestHeader("Content-type", "application/json");
      JsonClientPatientSearch.send(PatientSearch(PatientSearchCriteria,Credentials,Header));    

    JsonClientPatientSearch.onload = function(){

    };
    JsonClientPatientSearch.onerror = function(e){

    };

我的项目中有很多JSON调用,我是否可以编写一个类并使用其实例来进行JSON调用...只是传递参数...

2 个答案:

答案 0 :(得分:2)

您可以创建对象的实例并重用它们。您的代码看起来像这样:

var MyCall = function(url, onLoad, onError){
    // API Url to call
    this.url = GetAPIUrl() + url;
    this.onLoad = onLoad;
    this.onError = onError;
};
MyCall.prototype = {
    call: function(){
        var JsonClientPatientSearch = Titanium.Network.createHTTPClient();
        JsonClientPatientSearch.open("POST", this.url);
        //setting Request Header
        JsonClientPatientSearch.setRequestHeader("Content-type", "application/json");
        JsonClientPatientSearch.send(PatientSearch(PatientSearchCriteria,Credentials,Header));    
        JsonClientPatientSearch.onload = this.onLoad;
        JsonClientPatientSearch.onerror = this.onError;

    }
};

// create callbacks
var myLoad = function(response){ /* do something with response */ },
    myError = function(error){ /* do something with error  */ };
// create instance
new MyCall("PatientSearch", myLoad, myError);
// do a call
MyCall.call();

您需要根据需要如何处理其他全局对象来调整它。但希望这会让你朝着正确的方向前进。

答案 1 :(得分:2)

为什么不在编写自己的AJAX框架时省去麻烦,例如优秀的jQuery库?

http://api.jquery.com/jQuery.ajax/