Javascript function not returning properly?
function IsSwap()
{
var urlString = "<%= System.Web.VirtualPathUtility.ToAbsolute("~/mvc/Indications.cfc/GetModelType")%>";
var id =
{
id : GetGUIDValue()
}
$.ajax({
type: "POST",
url: urlString,
data: id,
success: function(data) {
if (data.toString() == 'SwapModel')
{
return true;
}
}
});
Expected result is true
. I can alert right before the return so I know it's getting to that point fine. In another function, I tried to get my bool and开发者_开发问答 use it like this:
var isSwap = IsSwap();
if (isSwap)
and it keeps saying isSwap
is undefined. Why?
You are using ajax requests, which are asynchronous. You can't return value from an ajax request. Try this instead:
function IsSwap()
{
var urlString = "<%= System.Web.VirtualPathUtility.ToAbsolute("~/mvc/Indications.cfc/GetModelType")%>";
var id =
{
id : GetGUIDValue()
}
$.ajax({
type: "POST",
url: urlString,
data: id,
success: function(data) {
if (data.toString() == 'SwapModel')
{
ResultIsTrue(); // call another function.
}
}
});
After execution, instead of using this:
var isSwap = IsSwap();
if (isSwap){
// Do Somethinh
}
Try that:
IsSwap();
function ResultIsTrue(){
// Do Same Thing
}
You can't return from an ajax call like that.
Essentially what you're doing is returning true from the inner function.
You should just call whatever code you need in the success method as that's the only time you can guarantee that the ajax call has completed.
The AJAX request is asynchronous, meaning that IsSwap
will return before the response to the AJAX request.
Whatever you need to do based on isSwap
, you should do in the success handler of your AJAX request.
UPDATE: This last paragraph is incorrect about it working, but worth noting about synchronous not being recommended:
Alternatively, you could make the AJAX request synchronous (by adding async:false
to the AJAX options) and keep it how you have it - however I wouldn't recommend this as your browser will 'freeze' whilst it waits for the response.
Check this line:
var urlString = "<%= System.Web.VirtualPathUtility.ToAbsolute("~/mvc/Indications.cfc/GetModelType")%>";
Try using single quotes like so:
var urlString = '<%= System.Web.VirtualPathUtility.ToAbsolute("~/mvc/Indications.cfc/GetModelType")%>';
Your double quotes inside double quotes is most likely your problem.
精彩评论