Вопрос

I have this javascript:

$ajax = $.ajax({
    type: 'GET',
    url: 'DBConnect.php',
    data: '',
    dataType: 'json', 
    success: function(data) {},
    error:function (xhr, ajaxOptions, thrownError) {
        dir(thrownError);
        dir(xhr);
        dir(ajaxOptions);
    }
});
console.dir($ajax);
console.dir($ajax.responseJSON);

console.dir($ajax) shows it has a property named responseJSON, but when I try to access it with $ajax.responseJSON it returns undefined: enter image description here

Это было полезно?

Решение

Well, of course it's undefined, because at the moment when you run console at last lines of your code, response hasn't yet came from the server.

$.ajax returns promise, which you can use to attach done() and fail() callbacks, where you can use all the properties that you see. And you have actually used callback error and success, and that's where you can run code and other functions that rely on data in the response.

Другие советы

You can use this trick to get the response out:

jQuery.when(
    jQuery.getJSON('DBConnect.php')
).done( function(json) {
    console.log(json);
});

It's late but hopefully will help others.

The response, is the "data", in success... so you can access to that writing data[0], data[1], inside the success.

For example:

success: function(data) {
 alert(data[0]);
},

If you want this response, out of the success, you can set a variable outside, and try this:

success: function(data) {
 myVar = data;
},

Hope, this help.

For those who don't really mind if it's synchronous, like I was, you can do this:

$('#submit').click(function (event) {
    event.preventDefault();

    var data = $.ajax({
        type: 'POST',
        url: '/form',
        async: false,
        dataType: "json",
        data: $(form).serialize(),
        success: function (data) {
            return data;
        },
        error: function (xhr, type, exception) {
            // Do your thing
        }
    });

    if(data.status === 200)
    {
        $('#container').html(data.responseJSON.the_key_you_want);
    }
});

It runs through the motions, waits for a response from the Ajax call and then processes it afterwards if the status == 200, and inside the error function if something triggered an error.

Edit the options to match your situation. Happy coding :)

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top