Reputation: 343
I am updating historic JS code from another author but having problems converting the below to the JQuery alternative:
var xhr = new XMLHttpRequest();
xhr.open('GET', songurl, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
document.getElementById('songdiv').innerHTML = '';
song.src = (window.webkitURL ? webkitURL : URL).createObjectURL(this.response);
}
}
xhr.send();
This is more so to aide consistency, Chrome - developer tools is also suggesting the code to be re-factored.
Here is what I have started with (appreciate it's not much!), the issue I'm having is checking the status code and returning the response if the status code is 200.
$.ajax({
url: songurl,
method: 'GET'
);
Upvotes: 1
Views: 61
Reputation: 3940
You want to attach a function for success.
$.ajax({
url: songurl,
method: 'GET',
success: function(response){
//do stuff with response
}
})
Upvotes: 2
Reputation: 36438
ajax()
, or the shorthand get()
, will do all that for you. There's a success()
function that's only called on a successfull, 200-status request:
$.get( songurl,
function(data) {
document.getElementById('songdiv').innerHTML = '';
song.src = (window.webkitURL ? webkitURL : URL).createObjectURL(data);
},
'blob'
);
Upvotes: 1