jQuery and AJAX
Can anyone help with a jQuery snippet that would use Ajax to pull an XML file in on page load?
Have really clunky way of doing it without jQuery here:
<script type="text/javascript">
function loadXMLDoc()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
xmlDoc = xmlhttp.responseXML;
var txt = "";
x = mlDoc.getElementsByTagName("title");
for (i=0;i<x.length;i++)
{
txt = txt + x[i].childNodes[0].nodeValue + "<br />";
}
document.getElementById("checked开发者_如何学运维In").innerHTML=txt;
}
}
xmlhttp.open("GET", "data.xml", true);
xmlhttp.send();
}
</script>
Ideally rather the having a click generate the list it would do so on page load, showing the fields from the XML (title, author, and whether it is checked in or not)
Would hug you for a solution
$( function() {
$.ajax( {
url: 'ajax.xml',
type: 'GET',
dataType: 'xml',
success: function( response ) {
var books = $( response ).find( 'book' );
var list = $( '#booklist' );
$( books ).each( function() {
var checkedOut = ( $( this ).attr( 'checked-out' ) == '1' );
var title = $( this ).find( 'title' );
var li = $( '<li></li>');
if( checkedOut ) {
li.addClass( 'selected' );
}
li.html( title );
list.append( li );
});
}
});
});
why dont you use jquery simple ajax request?
$(document).ready(function() {
$.ajax({
url: "file.xml",
dataType: "xml",
success: function() {
// on success here
}
});
});
精彩评论