javascript - Why am i receiving error 404 when fetching video data?
I'm trying to display the video which is in mp4 format of the code's folder. When i try to fetch the video by clicking on the button it shows an empty space but doesn't display the video.display of the output
The error i'm receiving from the console: GET http://127.0.0.1:8080/myapi/myapi1/undefined 404 (Not Found)
Below is the url to display the json data: http://localhost:8080/myapi/myapi1/user/1
The link above displays:
{"videoName":"video.mp4"}
The code to fetch the video and display using ajax:
$('#room1').on('click',function (e){
$.ajax({
method: "GET",
cache: false,
dataType: "json",
url: "http://localhost:8080/myapi/myapi1/user/1",
success: function(data) {
var student = '';
// ITERATING THROUGH OBJECTS
$.each(data, function (key, value) {
// DATA FROM JSON OBJECT
student += '<video height="603"';
student += 'src="' +
value.videoName + '" autoplay loop muted></video>';
});
$('#video').append(student);
},
error:function(exception){alert('Exeption:'+exception);}
})
e.preventDefault();
});
Answer
Solution:
So, The data you are fetching is in JSON ENCODED FORMAT. so you need to parse it to a JS Object. like this: data = JSON.parse(data)
in your success
function.
Answer
Solution:
(1) Since you only have one data item returned, please change the success block from:
success: function(data) {
var student = '';
// ITERATING THROUGH OBJECTS
$.each(data, function (key, value) {
// DATA FROM JSON OBJECT
student += '<video height="603"';
student += 'src="' +
value.videoName + '" autoplay loop muted></video>';
});
$('#video').append(student);
},
to
success: function(data) {
var student = '';
// DATA FROM JSON OBJECT
student += '<video height="603"';
student += 'src="' +
data.videoName + '" autoplay loop muted></video>';
$('#video').append(student);
},
data.videoName is already the data (video filename) you need
(2) However, if you have multiple data, like the following:
[{"videoName":"video.mp4"}, {"videoName":"video1.mp4"}]
then you may use the following :
success: function(data) {
var student = '';
for (var x = 0; x < data.length; x++) {
// DATA FROM JSON OBJECT
student += '<video height="603"';
student += 'src="' +
data[x].videoName + '" autoplay loop muted></video>';
}
$('#video').append(student);
},
data[index].videoName will be the data (video file name) for each index
(3) If you still prefer to use key / value pairs, the correct syntax will be like:
$.each(data, function (key, value) {
alert(data[key].videoName);
})
Source