Reputation: 4801
Im forced to deal with an XML file that has multiple & in it, similar to :
<row>
<value>Boys & Girls</value>
</row>
Heres my method :
$.ajax({
type : "POST",
url : "data.xml",
dataFilter : XMLFilter, //handles raw response data of XMLHttpRequest. pre-filtering to sanitize response.
async : false, //false means this has to complete before continuing
success : XMLLoadedSuccess, //to be called if the request succeeds.
error : function (XMLHttpRequest, textStatus, errorThrown) { debugger; },
complete : XMLLoadedComplete //called when the request finishes after success / error callbacks are executed
});
The error is reported as :
textStatus : parse error
errorThrown : InvalidXML
Digging into the error, Im 99.99% sure its the & symbol peppered throughout.
I thought maybe the dataFilter parameter could be used to sanitize the response, but that seems to be called only after success. I was trying to do something like
function XMLFilter(data, type) {
data = data.replace("&", "and");
return data;
}
with it, but thats aparently not how to do this.
Then I thought, use php to load / filter out the & and write a new XML file, and have jQuery use that. This might work, but the XML file is like 500k in size. So maybe have a cron job that only does that once a day when the new XML is generated.
Bashing the person responsible for allowing the & in there is also an option but I dont see how it will help the end user.
Whats a good way to handle this?
Upvotes: 0
Views: 73
Reputation: 2814
Your $.ajax()
doesn't specify dataType
. Because url
setting has .xml extension, JQuery infers the transferred data are XML (see: http://api.jquery.com/jquery.ajax). This is wrong because of & incorrect encoding. You have to indicate that you want to transfer data as text with dataType: 'text'
and then you process them.
In your case, data processing involves three steps:
This can be written:
$.ajax({
...
url: "data.xml",
dataType: 'text',
success: function(data) {
var xml = jQuery.parseXML(data.replace("&", "&"));
process(xml);
},
...
});
Upvotes: 2