tags:

views:

263

answers:

1

Can someone tell me how to change this getJSON request to a .ajax call so I can set the contentType option?

$.getJSON('json/showreel.json', function(data) {
    //get total number of JSON objects and generate random numder
    var total = data.length;
    var randnum = Math.floor(Math.random()*total)

    //Loop through each of the JSON objects to check if matches random number
    $.each(data, function(entryIndex, entry) {

        if(entryIndex === randnum){
            var info = '<div class="entry" style="color:' + entry['colour'] + '">';
            info += entry['title'] + '<br />';
            info += '<a href="' + entry['link_url'] + '">' + entry['website'] + '</a>';
            info += '</div>';

            $('#head-contact,#head-contact a').css('color',entry['colour']);

            //create new image object to preload image
            var img = new Image();
            //once image has loaded execute this code
            $(img).load(function () {
                //$(this).css('display', 'none'); // .hide() doesn't work in Safari when the element isn't on the DOM already
                $(this).hide();
                $('#showreel').removeClass('loading').append(this);
                $(this).fadeIn(3000);
            }).error(function () {
                // notify the user that the image could not be loaded
            }).attr('src', entry['image_src']);
        }
        $('#info').append(info);
    });
});

Many thanks, C

+1  A: 

contentType is used to set the type of sent data. GET requests do not send data so you may be talking about the type of received data, this is changed using the dataType option.

Replace:

$.getJSON('json/showreel.json', function(data) {
    ...
});

by:

$.ajax({
    type: 'get',
    url: 'json/showreel.json',
    dataType: 'application/json'
    success: function(data) {
        ...
    }
});
Vincent Robert
...or if you have control over the response yourself, then you really need to change this in the server side.
BalusC
When I add the code inside the success function it doesn't work
Model Reject
You'll need to give more information than "doesn't work". Did it crash with an error? Did it do something? Is the JSON in your response valid (jsonlint.com)?
Vincent Robert
Ah. Got it sorted. there was just no response with data. Thanks
Model Reject