ajax call inside a function

▼魔方 西西 提交于 2019-12-25 02:47:19

问题


i have a function which does some task.inside the function i have an ajax call. if the response obtained from ajaxcall is true the function should continue with the rest of the task.else it should stop at that point itself. But the above said thing is not happening instead the function is executed independent of ajax call. please help me out in this

function f1(id)
{
var test= id
var url="contentserver?pagename=mandatory@id"=+id;
var ajax=new Ajaxrequest(url,validatecallback);
ajax.doGet();
if(id==true){
return;
}
........(some code which has to carried out after the ajax call)
}
function validatecallback
{
this function gets the response for the above mentioned ajaxcall
we are setting a global variable(i.e id) here so that we can use that we can retrieve that in function f1
}

回答1:


The function "f1" has a formal parameter called "id"; that's the variable it will test in the statement "if(id==true)". While it may be true that there is also a global variable called "id", and that the callback function will access and modify it, it is a different variable. A modification to it will not affect the test in f1.




回答2:


See my answer to this related question: How can I write an async method in JavaScript when posting or looping?

Basically you have to change your thinking. It needs to instead be something like:

function f1(id) {
  var test= id
  var url="contentserver?pagename=mandatory@id"=+id;
  var ajax=new Ajaxrequest(url,function (r) {
      validatecallback(r)
      if(id==true){
        return;
      }
      ........(some code which has to carried out after the ajax call)
  });
  ajax.doGet();
}


来源:https://stackoverflow.com/questions/3720696/ajax-call-inside-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!