2011-02-15 118 views
1

我有一个问题,我的JavaScript不等待电话回复。我现在已经是javascript了,所以我想知道如何让这个方法调用等待结果。自用户上传后,我无法控制前两个snipper。我可以使用jQuery或纯JavaScript。提前致谢!JavaScript在等待返回前继续

我有这个JavaScript调用

var value = somemethod("cmi.location"); 
//This is not getting set since it does not wait. alerts 'undefined' 
alert(value); 

和的someMethod看起来像下面的代码,

function somemethod(element){ 
var result; 
result = API1.GetValue(element); 
return result; 
} 

API是通过做下面的代码实例化一个窗口对象。从这一点我可以访问代码片段。

var API1 = new API(); 

API是在JavaScript对象,看起来像这样:

function API(){ 

}; 
API.prototype.GetValue=API_GetValue; 

function API_GetValue(parameter){ 
$.ajax({ 
    type:"POST", 
    async:false, 
    url:"method.do", 
    dataType:"xml", 
    data: {action: 'getValue', parameter: parameter, value: ''}, 
    success:function(data){ 
    //I am getting 0 here 
     return $(data).find('search').text(); 
    } 
}); 
} 

回答

3
function API_GetValue(parameter){ 
var newdata; 
$.ajax({ 
    type:"POST", 
    async:false, 
    url:"method.do", 
    dataType:"xml", 
    data: {action: 'getValue', parameter: parameter, value: ''}, 
    success:function(data){ 
    //I am getting 0 here 
     newdata = $(data).find('search').text(); 
    } 
}); 
return newdata; 
} 

你也可以做这样的事情:

function API_GetValue(parameter){ 
var newdata = $.ajax({ 
    type:"POST", 
    async:false, 
    url:"method.do", 
    dataType:"xml", 
    data: {action: 'getValue', parameter: parameter, value: ''} 
}).responseText; 
return $(newdata).find('search').text(); 
} 
+0

我已经尝试过这一点,但它仍然没有不行。我会再试一次,你能告诉我为什么你认为这会起作用吗? – mezzie 2011-02-15 14:09:11