In the below piece of code I am not getting the locale in the second alert

if `value==null`

I assign its locale value. but do not get it at the end.

function getLocale(id) {
    var locale="";
    var value = localStorage.getItem(id);
    if (value == null) {
        $.ajax({
            type: "POST",
            url: "myUrl",
            data: {"new" : id},
            success : function(data) {
                data = JSON.parse(data)
                var id = data[0]["id"];
                delete data[0]["id"];
                localStorage.setItem(id, JSON.stringify(data[0]));
                locale=JSON.stringify(data[0]);
                alert(locale);//corrects value
            }// end success
        });
    }else{
        locale= localStorage.getItem(id);
    }
    alert(locale+"locale");//not have the value
    return locale;
}
有帮助吗?

解决方案

Its not because of the scope. It is because of the asynchronous behaviour of ajax call. Because the function will not wait for the success event of ajax.

If you want to return, you should use async:false in ajax. But it is not a good method of coding.

Or you should restructure your code with the asynchronous ajax. Instead of returning the value, call a function in the ajax success with desired id.

其他提示

ajax request is an async process which means it has a different execution timing with your function returning a value.

the trick here is do not assume to have a return value in the scope of the function. do all the process in the success call back function

    success : function(data){
      //do everything what you want to do with the response here
    }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top