Javascript 传递返回值
请帮忙,我已经看了一整天了,我知道一定有一个简单的解决办法 如何将结果传回textService,以便我可以拨打以下电话: textResult=textService(要传入的文本) 如果可以避免,我不想使用全局变量。 这是密码Javascript 传递返回值,javascript,Javascript,请帮忙,我已经看了一整天了,我知道一定有一个简单的解决办法 如何将结果传回textService,以便我可以拨打以下电话: textResult=textService(要传入的文本) 如果可以避免,我不想使用全局变量。 这是密码 function textService(text){ req.open("GET", "http://....?text="+text, true); req.onload = showResults; req.send(null); } function sho
function textService(text){
req.open("GET", "http://....?text="+text, true);
req.onload = showResults;
req.send(null);
}
function showResults() {
results = req.responseXML.getElementsByTagName("Result");
}
提前感谢您您可以使用此
function showResults() {
results = this.responseXML.getElementsByTagName("Result");
}
请注意,发出同步请求可能是有害的,如果请求失败,可能会导致浏览器无法正常运行。最好是异步进行
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.
});
只需将您的编码思想转换为异步编程;)
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.
});