Sorry I should've said this earlier. JSON is more like an alternative to XML. To use JSON here's an example from a perl script called from an XMLHttpRequest. That's basically your standard AJAX technique.
This method is described here. If you were still interested in trying an XML solution you can look here. Granted that's a php solution, but you'd just print out the XML as i do in the first snipet of code with the JSON.
all in all it's just a matter of getting a string back from your perl script. Then using the request.responseText. Then doing whatever you want to that string; whether it's parsing XML or evaluating it to create a JavaScript Object. If your giving a string to your perl script, that's when you might use the JSON module to interpret the string into a perl object. If you still wanted to go the XML route, it's pretty much the same concept, except use an XML module to create/dump perl object from/to XML, then have the JavaScript interpret it. Looks like there's plenty XML modules on CPAN. Hope this helps.
Employee.pcgi
in this @employees is just an array of hashes
#header required to properly recieve text/html response
print "Content-type: text/html\n\n";
print '{"employees" : [' . "\n";
foreach my $employee(@employees) {
print '
{
"name" : "' . $employee->{name} . '",' . "\n" .
'"company" : "' . $employee->{company} . '",' . "\n" .
'"email" : "' . $employee->{email} . '",' . "\n" .
'"website" : "' . $employee->{website} . '"'. "\n" .
'},'
}
print ']}';
And here's what the javascript might look like.
employee.js
//loading XML (JSON) data
function loadXML(url)
{
//creating XMLHttpRequest Object... IE Only
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
req = false;
}
}
alert('contacting ' + url);
//opening url
req.open("GET",url, true);
//when data is recieved, goto popuplate_list()
req.onreadystatechange=populate_list;
//GET method, send null
req.send(null);
}
//populates a JSON object of employees
function populate_list()
{
//response completed
if(req.readyState == 4)
{
//response ok
if(req.status == 200)
{
//evaluate string into a JSON object
var records = eval('('+req.responseText+')');
//display records
show_list(records);
}
}
}
//showing employees
function show_list(records)
{
var size = records.employees.length;
var employee_list = records.employees;
for(var i=0; i<size; i++)
{
alert('Name ' + employee_list[i].name + '\n' +
'Company ' + employee_list[i].company + '\n' +
'Email ' + employee_list[i].email + '\n' +
'Website ' + employee_list[i].website);
}
}
//contacting perl script
loadXML('../backend/script/employee.pcgi');
|