2010-08-09 91 views
1

请帮忙,我一直在看这一整天,我知道必须有一个简单的修复!传递返回值

如何将结果返回给textService,以便我可以拨打电话,例如 textResult = textService(要传入的文本);

我不想使用全局变量,如果我可以避免它。 这是代码

function textService(text){ 
req.open("GET", "http://....?text="+text, true); 
req.onload = showResults; 
req.send(null); 
} 

function showResults() { 
results = req.responseXML.getElementsByTagName("Result"); 
} 

预先感谢您

回答

0

您可以使用这个

function showResults() { 
    results = this.responseXML.getElementsByTagName("Result"); 
} 
2
function textService(text){ 
    // set flag to false for sync requests 
    req.open("GET", "http://...?text="+text, false); 
    req.send(null); 
    // browser will be stalled till request is complete. 
    if(req.status == 200 && req.readyState == 4) { 
     return req.responseXML.getElementsByTagName("Result"); 
    } else { 
     return 'request failed'; 
    } 
} 
// javascript will stall till request is complete. 
var results = textService('someText'); 

注意,使得同步请求可能是有害的,如果请求失败,它可能会无休止地拖延浏览器。不同步更好。

function textService(text, callback){ 
    // async is true by default, no need to pass 3rd param. 
    req.open("GET", "http://...?text="+text); 
    req.send(null); 
    req.onreadystatechange = function(){ 
     if(this.readyState == 4 || this.status == 200) { 
      callback(this.responseXML); 
     } 
    } 
} 
textService('someText', function(xml){ 
    // do stuff with XML. 
}); 

只需要你的编码的头脑切换到异步编程;)