javascript - How to return multiple values from an ajax success event -
i have 2 js files i.e. myjs1.js , myjs2.js . myjs1.js method of myjs2.js called.
i want return r1
, r2
results(in myjs1.js)
i have tried this: declared r1
, r2
variables before ajax call , after ajax call added:
return [r1,r2];
but return r1
, r2
undefined
. when researched issue came across adding async: false
work has many issues (like browser freezing). tried , still not able values of r1
, r2.
note: uing ajax first time bear in mind.
edit: there ajax call in js1 in on success event method called. want access result call method in js1
edit:look here code
myjs1:
function method() { $.ajax({ type: "get", datatype: "json", url: "http://127.0.0.1:8000/***/***", success: function(response){ result=methodofmyjs2(response); load1(r1); //r1 result load2(r2); //r2 result } })
}
myjs2 :
function methodofmyjs2(data) { $.ajax({ type: "get", data:somedata, datatype: "json", url: "http://127.0.0.1:8000/***/***", success: function(response){ r1=anothermethodfromthisjs1(response); r2=anothermethodfromthisjs2(response); result=[r1,r2] } })
}
i need access value of r1 , r2 call load1 , load2 method of myjs1.
ajax calls asynchronous
default, meaning ajax call function jquery.ajax()
wont wait http response come before returning.
to data after http response has arrived have provide callback, that's success
function. if want data inside function call function inside success
callback.
following code:
//js1. function processresponse(r1, r2) { // processing here r1 , r2 } //js2. function methodofmyjs2() { $.ajax({ type: "get", data:somedata, datatype: "json", url: "http://127.0.0.1:8000/****/****", success: function(response){ r1=anothermethodfromthisjs1(response); r2=anothermethodfromthisjs2(response); //calling success callback processresponse(r1, r1); } }); }
there's option if want it, can make ajax call synchronous
below.
$.ajax({ type: "get", url: remote_url, async: false,//now call synchronous success : function (data) { } });
now jquery.ajax()
wait till http response has arrived, can return [r1, r2]
methodofmyjs2()
.
however should avoid making synchronous calls make js thread wait freezing ui.
Comments
Post a Comment