如何使用javascript调用钛中的WebService

时间:2012-01-03 07:12:51

标签: javascript titanium appcelerator appcelerator-mobile titanium-mobile

我是钛的新手,想从我的钛应用程序中调用一个Web服务。 webService返回json响应。 我知道使用XMLRPC调用webService但是对于json非常困惑。

到现在为止,我知道我们必须创建HTTPClient

var request = Titanium.Network.createHTTPClient();
request.open("POST", "http://test.com/services/json");
request.onload = function() {
    var content = JSON.parse(this.responseText);//in the content i have the response data
};

request.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //did not understand this line
request.send();

现在问题是如果我的url(端点)有很多WebServices,那么我将给出方法名称,即要调用的WS名称。

从Titanium mobile的API文档中,函数openrequest.open接受3个参数:

  1. 方法名称(http方法名称)

  2. 请求网址

  3. async(boolean property)默认为true。

  4. 在上面的代码中"POST"做什么?如果我的WS名称是system.connect那么我将在代码中提到它?

    如果WS需要参数,那么我们如何将参数发送到上面代码的webService。

    我知道request.send()可用于发送参数但是如何发送?

1 个答案:

答案 0 :(得分:14)

要调用网络服务,您应该:

    // create request
    var xhr = Titanium.Network.createHTTPClient();
    //set timeout
    xhr.setTimeout(10000);

    //Here you set the webservice address and method
    xhr.open('POST', address + method);

    //set enconding
    xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");

    //send request with parameters
    xhr.send(JSON.stringify(args));

    // function to deal with errors
    xhr.onerror = function() {

    };

    // function to deal with response
    xhr.onload = function() {
        var obj = JSON.parse(this.responseText);

    };

地址是您的网络服务网址。

方法是您想要调用的方法。

address + method是一个URL,在您的示例中:“http://test.com/services/json”调用的方法将命名为json。

args :是一个json对象,其变量名称应与webservice参数具有完全相同的名称。您可以像这样创建参数对象:

var args = {};
args.parameter1 = 'blabla';
args.parameter2 = 'blaaaa';
相关问题