How to call WebService in titanium using javascript

I am new to titanium and want to call a web service from my titanium app. WebService returns a json response. Since I am aware of calling webService using XMLRPC , but very confusing regarding json.

So far, I know that we must create an 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(); 

Now the problem is that my url (endpoints) have many WebServices, so when I give the method name ie the name WS, which should be called.

From the Titanium mobile API documentation, the open ie request.open function accepts 3 parameters:

  • method name (http method name)

  • Request url

  • async (boolean property) is true by default.

In the above code, what does "POST" do there? and if my name is WS system.connect , then where will I mention that in the code?

And what if WS needs a parameter, since we can send this parameter to the webService formula with the code above.

I know that request.send() can be used to send a parameter, but like <

+4
source share
1 answer

To call a web service, you must:

  // 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 is your web service url.

method is the method you want to call.

address + method is the URL in your example: "http://test.com/services/json", the called method will be called json.

args : this is a json object where the variable names must have the same name as the webservice parameters. You can create a parameter object as follows:

 var args = {}; args.parameter1 = 'blabla'; args.parameter2 = 'blaaaa'; 
+14
source

Source: https://habr.com/ru/post/1389024/


All Articles