I am trying to get XML response in javascript array like:
<script type="text/javascript">
var arrayName = [];
var arrayValue [];
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "data.xml",
dataType: "xml",
success: function(xml) { parseXml(xml); }
});
});
function parseXml(xml)
{
$(xml).find("category").each(function()
{
arrayName.push($(this).find("name").text());
arrayValue.push($(this).find("value").text());
});
}
//Do some javascript stuff using arrayName and arrayValue for example:
alert(arrayName[0]);
alert(arrayValue[0]);
</script>
But I am not able to get xml response in javascript array.
my XML file is :
<?xml version="1.0" encoding="utf-8" ?&开发者_Python百科gt;
<data>
<category id="category1">
<name>Error</name>
<value>41</value>
</category>
<category id="category2">
<name>Warning</name>
<value>23</value>
</category>
<category id="category3">
<name>Info</name>
<value>46</value>
</category>
</data>
please help me to solve this problem
I will repeat my comment here:
Put the alerts in the callback. They are executed before the response comes from the server. Ajax is asynchronous.
So basically you have to call all the code that has to deal with the response from your callback.
Example:
$(document).ready(function() {
$.ajax({
type: "GET",
url: "data.xml",
dataType: "xml",
success: function(xml) {
var items = parseXml(xml);
doStuff(items);
}
});
});
function parseXml(xml) {
var items = [];
$(xml).find("category").each(function() {
items.push({
name: $(this).find("name").text(),
value: $(this).find("value").text()
});
});
return items;
}
function doStuff(items) {
//Do some javascript stuff with the response
alert(items[0].name);
alert(tiems[0].value);
}
Callbacks are nothing special. As functions are first class objects in JavaScript, you can pass them around like any other value.
精彩评论