javascript - Scripting error in jQuery/AJAX code snippet? -
this should simple question, answer has eluded me time now. seem have error in code, either scripting typo, or error in logic. kindly clarify problem?
here's code:
function getquestion() { $.ajax({ type: "get", url: "questions.xml", datatype: "xml", success: function(xml) { x = 0; x = $(xml).find('question').length; var questionid = $.random(x); $(xml).find('question').each(function(){ if(this.id == questionid) { var text = $(this).find('body').text(); $('#questionbody')[0].innerhtml = text; } }); //close each } //close success });//close ajax }; //close function getquestion
it's meant read in xml file, search specific item random id, , plug contents of body
<p>
have in html file. however, isn't working expected. have made error?
thanks, elliot bonneville
this general observation , not answer, may in future:
//notice function easier consume in 1 glance function getquestion() { $.ajax({ type: "get", url: "questions.xml", datatype: "xml", success: getquestionsuccess });//close ajax }; //close function getquestion // <-superfluous semicolon? //notice function easier consume in 1 glance function getquestionsuccess(xml) { //let's quit querying each time need them var questions = $(xml).find('question'); //bonus, it's jquery object! //x = 0; // <-unnecessary assignment. gets obliterated on next line. x = questions.length; //the count of "question"s found var questionid = $.random(x); //but wait, read next comments below questions.each(function(){ if(this.id == questionid) { var text = $(this).find('body').text(); $('#questionbody')[0].innerhtml = text; } }); //close each //since seem looking index questionid of questions, //why not jump 1 instead of looping? //also, if have 1 "#questionbody" in document can more "jquery"ish. $('#questionbody')[0].innerhtml = questions[questionid].find('body').text(); //only one: $('#questionbody').html( questions[questionid].find('body').text() ); } //close success
so clarify :\
//i shredded down reasonable number of lines. shorter still, albeit less readable. //but think pretty readable. function getquestionsuccess(xml) { var questions = $(xml).find('question'); var questionid = $.random(questions.length); $('#questionbody').html( questions[questionid].find('body').text() ); } //close success
Comments
Post a Comment