javascript - 通用JSON调用类

标签 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 调用...只需传递参数...

最佳答案

您可以创建对象实例并重用它们。您的代码将如下所示:

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();

您需要根据需要如何与其他全局对象一起工作来调整它。但希望这能让您朝着正确的方向前进。

关于javascript - 通用JSON调用类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6289634/

相关文章:

javascript - JSONP 脚本返回 MIME 类型错误

javascript - 即使是最基本的 Javascript 对我来说也失败了 - 但为什么呢?

javascript - 为什么 ECMA 脚本不提供开箱即用的整数类型?

javascript - AngularJS - 如何使用表单添加到对象

javascript - 将具有特殊值的 JSON 对象作为字符串加载

c# - 从 RESTful API 加载许多 Base64 图像

javascript - 如何使用 Require JS 加载 JSON.js 库以使 Backbone 应用程序在 IE7 中运行?

php - jquery 在悬停时更改图像(然后返回初始图像)

javascript - Node.js 中的 promise 回调

javascript - jQuery Mobile 初始化所有元素