简体   繁体   中英

How can I parse a HTML attribute value out of XMLHttpRequest.responseText?

The below JS function does Ajax request and retrieves HTML in obj.responseText . My issue is that I need to extract the value of id inside the span into notify_id var. I just don't know how to get that done.

This is the HTML to lookup:

HTML:

<span id="1034"></span><img src="./images/icons/post_icon.png">

JS:

function func()
{
    obj = new XMLHttpRequest();
    obj.onreadystatechange = function() {
        if(obj.readyState == 4)
            jQuery.jGrowl(obj.responseText, { 
                sticky:true,
                close: function(e,m) {
                    notifyClosed(notify_id);

                }
            });
    }
    obj.open("GET", "notifications.php?n=1", true);
    obj.send(null);
}

Since you're already using jQuery:

var responseText = '<span id="1034"></span><img src="./images/icons/post_icon.png">';
var spanId = $('<div>').html(responseText).find('span').attr('id');
alert(spanId); // 1034

The whole function in turn can also be rewritten as follows:

$.get('notifications.php?n=1', function(responseText) {
    // Your code here.
});

See also the jQuery tutorials.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM