简体   繁体   中英

How to pass a PHP associative array to $.ajax with JSON

$.ajax seems to be broken for me:

$.ajax({url:'getGalleries.php', datatype:'jsonp',
    success: function(data){
        $('#galleries').html('');
        $.each(data,function(key,value) {
                $('#galleries').append(value);
        });
    },
    complete: function() { loading.hide(); }
});

The php is just passing:

<?php echo json_encode(array("associative"=>"arrays","are"=>"cool")); ?>

It seems to be fine with another function that uses just regular arrays, but for some reason my jQuery is spitting out a data that is an array of every character in the JSON string when I pass it a json encoded associative array.

The PHP page is grabbing a json list of image galleries then finding the first image in each gallery. I'm making an associative array with the gallery name as the index to then pass back to my html page to show each of my galleries and a sample image.

You have two problems. One is that datatype 's capitalization is incorrect; it should be dataType . Second, it isn't JSONP as far as I can see - it's JSON. So use 'json' as the dataType .

I am guessing that you need to capitalize dataType :

$.ajax({url:'getGalleries.php', dataType:'jsonp',
success: function(data){
    $('#galleries').html('');
    $.each(data,function(key,value) {
            $('#galleries').append(value);
    });
},
complete: function() { loading.hide(); }
});

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