jQuery return ajax result into outside variable

后端 未结 6 2022
栀梦
栀梦 2020-12-07 16:53

I have some problem using ajax.

How can I assign all result from ajax into outside variable ?

I google it up and found this code..

var return         


        
6条回答
  •  太阳男子
    2020-12-07 17:09

    'async': false says it's depreciated. I did notice if I run console.log('test1'); on ajax success, then console.log('test2'); in normal js after the ajax function, test2 prints before test1 so the issue is an ajax call has a small delay, but doesn't stop the rest of the function to get results. The variable simply, was not set "yet", so you need to delay the next function.

    function runPHP(){
        var input = document.getElementById("input1");
        var result = 'failed to run php';
    
        $.ajax({ url: '/test.php',
            type: 'POST',
            data: {action: 'test'},
            success: function(data) {
                result = data;
            }
        });
    
        setTimeout(function(){
            console.log(result);
        }, 1000);
    }
    

    on test.php (incase you need to test this function)

    function test(){
        print 'ran php';
    }
    
    if(isset($_POST['action']) && !empty($_POST['action'])) {
        $action = htmlentities($_POST['action']);
        switch($action) {
            case 'test' : test();break;
        }
    }
    

提交回复
热议问题