Ошибка скриптинга в фрагменте кода jQuery / AJAX? - PullRequest
0 голосов
/ 16 ноября 2010

это должен быть простой вопрос, но ответ уже ускользал от меня.Кажется, в этом коде есть ошибка, либо опечатка сценария, либо ошибка в моей логике.Не могли бы вы прояснить мою проблему?

Вот код:

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

Он предназначен для чтения в файле XML, поиска определенного элемента со случайным идентификатором и вставки содержимогоBODY в <p> У меня есть в моем HTML-файле.Тем не менее, это не работает, как ожидалось.Где я допустил ошибку?

Спасибо, Эллиот Бонневиль

Ответы [ 2 ]

1 голос
/ 16 ноября 2010

Это просто общее наблюдение, а не ответ, но оно может помочь вам в будущем:

//notice that this function is much easier to consume in one glance
function GetQuestion() {

    $.ajax({
        type: "GET",
        url: "questions.xml",
        dataType: "xml",
        success: GetQuestionSuccess
    });//close ajax

}; //close function GetQuestion  // <-superfluous semicolon?



//notice that this function is much easier to consume in one glance
function GetQuestionSuccess(xml) {

    //let's quit querying each time we need them
    var questions = $(xml).find('Question');  //bonus, it's a jQuery object!

    //x = 0; // <-unnecessary assignment. It gets obliterated on the next line.
    x = questions.length; //the count of all "Question"s found

    var questionID = $.random(x);

    //but wait, read my next comments below
    questions.each(function(){
        if(this.ID == questionID) {
            var text = $(this).find('BODY').text();
            $('#questionBody')[0].innerHTML = text;
        }
    }); //close each

    //since you seem to be looking for the index questionID of all the questions, 
    //why not jump to that one instead of looping?
    //also, if you only have one "#questionbody" in your document you can do this more "jquery"ish.
    $('#questionBody')[0].innerHTML = questions[questionID].find('BODY').text();

    //only one:
    $('#questionBody').html( questions[questionID].find('BODY').text() );

} //close success

чтобы уточнить: \

//I shredded it down to a reasonable number of lines. Could be shorter still, albeit less readable.
//but I think this is pretty readable.
function GetQuestionSuccess(xml) {

    var questions = $(xml).find('Question');

    var questionID = $.random(questions.length);

    $('#questionBody').html( questions[questionID].find('BODY').text() );

} //close success
0 голосов
/ 16 ноября 2010

Предположим, что ваш xml выглядит примерно так (поскольку вы его не публиковали) (обратите внимание на регистр символов в тегах)

<?xml version="1.0" encoding="ISO-8859-1"?>
<questionlist>
<Question ID='0'>
<BODY>
Are you 1?
</BODY>
</Question>
<Question ID='1'>
<BODY>
Are you 2?
</BODY>
</Question>
<Question ID='2'>
<BODY>
Are you 3?
</BODY>
</Question>
<Question ID='3'>
<BODY>
Are you 4?
</BODY>
</Question>
<Question ID='4'>
<BODY>
Are you 5?
</BODY>
</Question>
<Question ID='5'>
<BODY>
Are you 6?
</BODY>
</Question>
<Question ID='6'>
<BODY>
Are you 7?
</BODY>
</Question>
</questionlist>

Тогда вы можете использовать эту модифицированную версию вашего кода ...

<html>
<head>
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
       <script type="text/javascript">


function GetQuestion() {
        $.ajax({
            type: "GET",
            url: "questions.xml",
            dataType: "xml",
            success: function(xml) {
                x = 0;
                x = $(xml).find('Question').length;
                var questionID = Math.floor(Math.random() * x);

                $(xml).find('Question').each(function(){
                    if($(this).attr('ID') == questionID) {
                        var text = $(this).find('BODY').text();
                        $('#questionBody').html(text);
                    }
                }); //close each
            } //close success
        });//close ajax
    }; //close function GetQuestion

        $(document).ready(function(){
        GetQuestion();
        });
        </script>
</head>
<body>
<div id="questionBody"></div>
</body>
</html>

Я изменил метод $ .random, у меня не было этого метода, поэтому я использовал обычный JS, я изменил this.ID, чтобы использовать селектор jquery для проверки атрибута id, и я изменил вашу строку innerHTML, чтобы использовать функция jquery html (). Единственная проблема с кодом заключается в том, что вы полагаетесь на то, что у вас будут вопросы с идентификаторами n-1 записей ...

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...