简体   繁体   中英

Jquery Ajax responseText returns undefined but when i log it as an object it returns the ajax text

responseText returns undefined but when i log it as an object it returns the ajax text. I think it might have something to do with the readystate not being ready before it assigns the text to the variable

When I do this:

function loadTrack(){
    var min = -10;
    var max = 10;
    var randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
    var track = $.get("generate_song.php?track_number="+randomNumber);
        if(randomNumber > 0 && randomNumber !== previousNumber){
            previousNumber = randomNumber;
        }else{
            randomNumber = 1;
        }

       console.log(track);
}

I get this:

Object {readyState: 1, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
abort: function (e){var t=e||w;return u&&u.abort(t),k(0,t),this}
always: function (){return i.done(arguments).fail(arguments),this}
complete: function (){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this}
done: function (){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this}
error: function (){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this}
fail: function (){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this}
getAllResponseHeaders: function (){return 2===b?a:null}
getResponseHeader: function (e){var t;if(2===b){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t}
overrideMimeType: function (e){return b||(p.mimeType=e),this}
pipe: function (){var e=arguments;return x.Deferred(function(n){x.each(t,function(t,o){var a=o[0],s=x.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&x.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()}
progress: function (){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this}
promise: function (e){return null!=e?x.extend(e,r):r}
readyState: 4
responseText: "Audio_Files/09%20Dream%20of%20Witches%20Dinner%2C%20V%20mov.%20f.m4a.mp3<br/>"
setRequestHeader: function (e,t){var n=e.toLowerCase();return b||(e=v[n]=v[n]||e,y[e]=t),this}
arguments: null
caller: null
length: 2
name: ""
prototype: Object
__proto__: function Empty() {}
<function scope>
state: function (){return n}
status: 200
statusCode: function (e){var t;if(e)if(2>b)for(t in e)m[t]=[m[t],e[t]];else C.always(e[C.status]);return this}
statusText: "OK"
success: function (){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this}
then: function (){var e=arguments;return x.Deferred(function(n){x.each(t,function(t,o){var a=o[0],s=x.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&x.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()}
__proto__: Object

But when I do This:

function loadTrack(){
    var min = -10;
    var max = 10;
    var randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
    var track = $.get("generate_song.php?track_number="+randomNumber);
        if(randomNumber > 0 && randomNumber !== previousNumber){
            previousNumber = randomNumber;
        }else{
            randomNumber = 1;
        }

       console.log(track.responseText);
//or if i just do it when assigning track
}

I get this:

undefined script.js:41
XHR finished loading: "http://localhost/generate_song.php?track_number=10". jquery.js:6

You are kindof right, it is a timing problem. The jqXHR-Object exists, but responseText doesn't at the time you are assigning the object. But at the time of logging it does show. You shouldn't see the property of responseText if you log using console.log(JSON.stringify(track)) .

So, wait for the reply by using a callback for readyStateChange or alike mechanisms.

The problem comes with the logging functionality (I assume firebug or chrome's inspector?) that does not really freeze the object but show's it as it is at the time you look .

You are trying to use the results of the ajax call before the call has been completed. Javascript will keep executing all the code after the call has been made. Since you don't have any data, it is null until the call has been completed.

You want to modify your $.get() and pass it a function to execute when the call has been completed.

$.get("generate_song.php", {track_number: randomNumber}, function(track){
     console.log(track);
});

You can also just send the parameters without creating the url.

http://api.jquery.com/jQuery.get/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM