Jquery async and json data

following javascript jquery and using eval , I still can't get jquery to read data asynchronously.

 data1=[1,2,3,4]

Note: I included async: true in the example below to show the difference

Below example returns "null"

$(document).ready(function(){

var myArray=[];
myArray=getValues();
alert(myArray);
        function getValues(){
        var result=null;
             $.ajax({
                url: 'data1.html',
                type: 'get',
                dataType: 'json',
                cache: false,
                success: function(data) {result = data;},
                async:true,
                });
            return result;
        };
})

and below the example works fine and gives the result in the ie array [1,2,3,4]

$(document).ready(function(){

var myArray=[];
myArray=getValues();
alert(myArray);
        function getValues(){
        var result=null;
             $.ajax({
                url: 'data1.html',
                type: 'get',
                dataType: 'json',
                cache: false,
                success: function(data) {result = data;},
                async:false,
                });
            return result;
        };
 })

can anyone explain how to get the results asynchronously Thanks

+5
source share
4 answers

I would change it to this ...

$(document).ready(function(){

     function postProcessing(data) {
       var myArray = data;
       alert(myArray);
     }


    getValues();

        function getValues(){
             $.ajax({
                url: 'data1.html',
                type: 'get',
                dataType: 'json',
                cache: false,
                success: postProcessing,
                async:true,
                });
        };
})
+7
source

This should work, as it works in mine, but I suggest you not do it.

<script src="jquery.js"></script>
<script>
$(document).ready(function(){

    /*don't do your stuff here*/
        /*do inside success*/

    function getValues(){
        var result=null;
        $.ajax({
            url: 'phpinfo.php',
            type: 'get',
            dataType: 'json',
            cache: false,
            success: function(data) { if(data != null){ alert(data); } },
        });
        return result;
    };

})
</script>
+3
source

myArray, , . , " ", .

0

asynchronously. true .

, false. Cross-domain dataType: "jsonp" . , , , .

If you need to make sure that the method always displays the latest data, use cache:falseand async:false. Also, to avoid a timeout / error, use the success/ error/ completecallback options.

0
source

All Articles