开发者

Passing a return value

Please help, I have been looking at this all day and I know there must be a simple fix!

How do I pass results back to textService so that I can make a call such as textResult = textService(text to pass in);

I don't want to use a global variable if I can avoid it. This is the code

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

function showResults() {
results = req.responseXML开发者_Go百科.getElementsByTagName("Result");
}

Thank you in advance


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

Note, making synchronous request can be harmful, if a request fails, it might stall the browser indefinatly. It's better to do it asynchronously.

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.
});

Just need switch your coding mind to async programming ;)


You can use this

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜