views:

1280

answers:

3

I have a JSON result that contains numerous records. I'd like to show the first one, but have a next button to view the second, and so on. I don't want the page to refresh which is why I'm hoping a combination of JavaScript, jQuery, and even a third party AJAX library can help.

Any suggestions?

+1  A: 

I use jqgrid for just this purpose. Works like a charm.

http://www.trirand.com/blog/

clintp
+1  A: 

I would personally load the json data into a global variable and page it that way. Hope you don't mind my assumptions on the context of survey data I think I remember you from yesterday.

var surveyData = "[{prop1: 'value', prop2:'value'},{prop1: 'value', prop2:'value'}]"
$.curPage = 0;

$.fn.loadQuestion = function(question) {
    return this.each(function() {
     $(this).empty().append(question.prop1);
     // other appends for other question elements
    });
}

$(document).ready(function() {
    $.questions = JSON.parse(surveyData);  // from the json2 library json.org
    $('.questionDiv').loadQuestion($.questions[0]);     

    $('.nextButton').click(funciton(e) {
     if ($.questions.length >= $.curPage+1)
      $('.questionDiv').loadQuestion($.questions[$.curPage++]);
     else
      $('.questionDiv').empty().append('Finished');
    });
});

~ UnTested

I'll have to admit that @sktrdie approach of creating a whole plugin for handling the survey would be nice. IMO this method is really a path of least resistance solution.

bendewey
+2  A: 

Hope this helps:

var noName = {
    data: null
    ,currentIndex : 0
    ,init: function(data) {
        this.data = data;
        this.show(this.data.length - 1); // show last
    }
    ,show: function(index) {
        var jsonObj = this.data[index];
        if(!jsonObj) {
            alert("No more data");
            return;
        }
        this.currentIndex = index;
        var title = jsonObj.title;
        var text = jsonObj.text;
        var next = $("<a>").attr("href","#").click(this.nextHandler).text("next");
        var previous = $("<a>").attr("href","#").click(this.previousHandler).text("previous");

        $("body").html("<h2>"+title+"</h2><p>"+text+"</p>");
        $("body").append(previous);
        $("body").append(document.createTextNode(" "));
        $("body").append(next);
    }
    ,nextHandler: function() {
        noName.show(noName.currentIndex + 1);
    }
    ,previousHandler: function() {
        noName.show(noName.currentIndex - 1);
    }
};

window.onload = function() {
    var data = [
        {"title": "Hello there", "text": "Some text"},
        {"title": "Another title", "text": "Other"}
    ];
    noName.init(data);
};
Luca Matteis
Perfect. I'm actually putting together a plugin with that quiz sample I had mentioned yesterday. I'll post it as soon as I get it tweaked. Thanks again.
Jason N. Gaylord
Cool, glad this works, it needs some tweaking though.
Luca Matteis