Read XML file with jQuery

做~自己de王妃 提交于 2019-12-13 08:26:27

问题


I have an xml file in the form:

<cart>
<itemCount>1</itemCount>
<cartTotal>33.94</cartTotal>
</cart>

This is to track what is in the contents of an ecommerce shopping cart. So it will always only have one "cart" node.

I want to read the "cartTotal" field. If it is greater than 0, then I want to display my "View cart" button on the website.

I've tried the following and it isn't working:

$(document).ready(function(){
    $.ajax({
        type: "GET",
        url: "https://www.example.com/file.xml",
        dataType: "xml",
        success: function(xml) {
            $(xml).find('cart').each(function(){
                if (($(this).attr('cartTotal')) > 0) {
                    $("a.view-cart-button").css('visibility', 'visible');
                }
            });
        }
    });
});

回答1:


The elements within <cart>...</cart> are not attributes but child nodes.

Replace:

if (($(this).attr('cartTotal')) > 0) {
    $("a.view-cart-button").css('visibility', 'visible');
}

With:

if ( $('cartTotal',$(this)).text()*1 > 0) {
    $("a.view-cart-button").css('visibility', 'visible');
}

AMENDMENT

With the caveat that calling XML files, using AJAX, on another domain and without CORS access in place, this will fail, try the following:

$(document).ready(function(){

    $.ajax({
        type: "GET" ,
        url: "https://secure.ultracart.com/cgi-bin/UCJavaScript?merchantid=DEMO&type=xml" ,
        dataType: "xml" ,
        success: function(xml) {
            if( $(xml).find('cartTotal').text()*1 > 0 ){
                $("a.view-cart-button").css('visibility', 'visible');
            }
        }
    });

});​

If you are dealing with a payment gateway, or similar, refer to their documentation first - they will specify how you can interact with them from your own site.



来源:https://stackoverflow.com/questions/13390722/read-xml-file-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!