[英]How to use callback function in javascript
I'm building this code to calla web service. 我正在将此代码构建到马蹄铁Web服务。 Now I want that this method return an object.
现在,我希望该方法返回一个对象。
So this is the command that call the method: 因此,这是调用该方法的命令:
Titanium.API.info("CHIAMO IL WS CON DATA NULL");
getDocument("CFDECTEST02",null, function(obj) {
Titanium.API.info("CALL BACK CHIAMATA "+ obj);
});
This is the method that call web service: 这是调用Web服务的方法:
function getDocument(fiscalCode, date){
var obj;
var xhr = Titanium.Network.createHTTPClient();
xhr.setTimeout(10000);
xhr.open('POST', "http://url");
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
var myObject = {
cf :fiscalCode,
date_last_synchronization :date
};
xhr.send(JSON.stringify(myObject));
xhr.onerror = function() {
Ti.API.info("SERVIZIO IN ERRORE");
Ti.API.info(this.responseText);
disattivaSemaforo();
};
xhr.onload = function() {
var obj = JSON.parse(this.responseText);
Ti.API.info(this.responseText);
return obj;
};
}
The problem is on the callback function. 问题出在回调函数上。 Because the method getDocument call correctly the web service and have a correct obj, but the callback function is not called.
因为方法getDocument可以正确调用Web服务并具有正确的obj,但是未调用回调函数。
You need a third argument to your getDocument function (it will be the callback function of your xhr request) 您需要第三个参数传递给getDocument函数(它将是您的xhr请求的回调函数)
function getDocument(fiscalCode, date, success){
var obj;
var xhr = Titanium.Network.createHTTPClient();
xhr.setTimeout(10000);
xhr.open('POST', "http://url");
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
var myObject = {
cf :fiscalCode,
date_last_synchronization :date
};
xhr.send(JSON.stringify(myObject));
xhr.onerror = function() {
Ti.API.info("SERVIZIO IN ERRORE");
Ti.API.info(this.responseText);
disattivaSemaforo();
};
xhr.onload = xhr.onload = function() {
var obj = JSON.parse(this.responseText);
Ti.API.info(this.responseText);
success(obj);
};
}
Then you can call getDocument function as you did before 然后,您可以像以前一样调用getDocument函数
getDocument("CFDECTEST02",null, function(obj) {
Titanium.API.info("CALL BACK CHIAMATA "+ obj);
});
You treat it like any other function and any other argument. 您将其视为任何其他函数和任何其他参数。
You are passing it as the third argument to getDocument
, but you haven't give it a name in that function: 您将其作为第三个参数传递给
getDocument
,但尚未在该函数中为其命名:
function getDocument(fiscalCode, date){
should be: 应该:
function getDocument(fiscalCode, date, callback) {
Then you just need to call it: 然后,您只需要调用它:
var obj = JSON.parse(this.responseText);
callback(obj);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.