Ajax appearing as undefined

社会主义新天地 提交于 2020-01-17 08:21:23

问题


So I'm currently working on this website app and I'm trying to show how many PC's are available in my University using the JSON from the University website and AJAX. I can't figure it out but its showing all the MACs for the first room and then its saying undefined for others, its all one block of code so I can't see where its going wrong any advice would be great.

JS:

    var container = $('div.container');
$('input#get').click(function(){
    $.ajax({
        type: 'GET',
        url: '(mylink)',
        dataType: 'jsonp',
        success: function(data) {
        $.each(data, function(index, item) {
        $.each(item, function(key, value) {
            container.append('<div class="pcsinside">' + value.displayName + '</div>' + 'PCs available:' + '&nbsp' + value.availPCs + '&nbsp' + 'out of' + '&nbsp' + value.numPCs + '<br/>' + 'Macs available:' + '&nbsp' + value.availMacs + '&nbsp' + 'out of' + '&nbsp' + value.numMacs + '<br/>');
           });

          });

         }
     });
})

HTML:

<div class="container">
            <div id="form-area">
            <input id="get" type="submit" value="Press For PC Availability">
            </div>
            <div class="pcsinside">
            </div>
        </div>

This is what it looks like and it does update whenever a PC changes for the PC's and the MACs except for the undefined ones.

It works for the first one but not for the other MACs, whats going on? Any help would be really appreciated thanks guys.


回答1:


First in dataType you put 'jsonp' instead of 'json'. And S Jayesh is right, you must stringify to see the answer. See this exemple.

$.ajax({
    url: "blabla.php",
    data: data,
    type: 'POST',
    contentType: "application/x-www-form-urlencoded",
    dataType: 'json',
    error: function(data){
        var err = JSON.stringify(data);
alert(err);
    },
    success: function(data){
        var succ = JSON.stringify(data);
alert(succ);
    }
});

With that structure, you'll see what is the problem. Use post instead of get, it's better.




回答2:


To display JSON as string you need to use JSON.stringify() function :

container.append('<div>'+ JSON.stringify(value.displayName) +'</div>');


来源:https://stackoverflow.com/questions/43774003/ajax-appearing-as-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!