jQuery类返回undefined [重复]

问题描述:

This question already has an answer here:

I try to create a simple ajax request class in jQuery. The problem I have here is that in the process function I can get the response from variable response . I return response but outside the request it is undefined .. I tried with global variables of some sorts, didn't work out. So now I try to get help from here.

The app.js

var AjaxRequest = Class.extend({

    init: function(url) {
        this.url = url;
    },

    process: function() {

        var response;

        $.get("http://test.dec/ajax.php", function(data) {
            var obj = jQuery.parseJSON( data);
            response = obj;

            console.log(response); // Get correct output

            return response;
        });

    }

});

$('#test').on('click', function() {
    var request = new AjaxRequest('ajax.php');

    console.log(request.process()); // Get undefined
});

The PHP ajax.php

<?php

$json = json_encode(['test' => 'test123']);
echo $json;

?>
</div>

The problem is that ajax requests are asynchronous. What you want to do maybe is pass in a callback to process so when it completes, it will call the function to continue.

Here is an example:

var AjaxRequest = Class.extend({

    init: function(url) {
        this.url = url;
    },

    process: function(callback) {

        var response;

        $.get("http://test.dec/ajax.php", function(data) {
            var obj = jQuery.parseJSON( data);
            response = obj;

            console.log(response); // Get correct output

            callback(response);
        });

    }

});

$('#test').on('click', function() {
    var request = new AjaxRequest('ajax.php');

    request.process(function(data) { console.log(data); });
});

Please have a read through this on how asynchronus calls work.

please Try this:

$.ajax({
            url: 'your url',
            global: false,
            type: 'POST',
            data: {},
            async: false,
            success: function() {}
        });