开发者

jQuery: how to select attribue in this situation?

In my jQuery ajax method, the "data" it returns as following format:

<root>
    <result sender='BlackSmith' nickName='Blac'></result>
    <result sender='AristleJohnson' nickName='AJ'></result>
    .
    .
    .
</root>

In my jQuery function, my code is:

$(data).find('result').each(function()开发者_StackOverflow{ 
    alert("test");//it never shows up, I don't know why?
    var userId=$(this).attr('sender');
    var nickName=$(this).attr('nickName');
});

However, the alert never shows up, which means $(data).find('result') does not work here. Could you help me? Thank you.


I don't think you can pass HTML/XML into jQuery as you are with $(data). Typically, the DOM in question is already on the page somewhere, and you do $("result") instead.

In your case, you should dataType to "xml" in the ajax request itself, and then jQuery will actually parse the results and give them to you in your success() handler.

$(document).ready(function(){
    $.ajax({
        type: "GET",
        url: "/sites.xml",
        dataType: "xml",
        success: function(xml) {
            $(xml).find('result').each(function(){
                    ...
                });
            });
        }
    });
});


Assuming you're assigning the return value of the ajax call to the data variable, everything looks good - some things to check:

  • Try explicitly setting the dataType as XML
  • Double check what you're getting back from the server and that the response isn't 500ing, 404ing, or returning an empty response for any other reason


My first thought is that your dataset doesn't actually contain the response. Is $(data).find... actually inside the AJAX call? Once you leave the scope of the success: function, your response will be destroyed.

So most importantly, check scope:

$.ajax({
        type: "GET",
        url: "[yoururl]",
        dataType: "xml",
        success: function(data) {
          //this is the only place your $(data) selector will work...
    }
});

If you want to use data elsewhere, you're going to have to pass it out of your ajax call.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜