PHP
echo '<data><![CDATA[ [{"x":0,"y":0,"src":"images/image.jpg"}] ]]></data>';
JS
$.post( 'getData.php', {}, _onResult );
_onResult = function( result)
{
console.log(result);
}
The above console.log outputs:
( on localhost, using WAMP ):
<data><![CDATA[ [{"x":0,"y":0,"src":"images/image.jpg/"}] ]]></data>
( on web hosting, using LINUX ):
<data><![CDATA[ [{"/x/":0,/"y/":0,/"src/":/"images/image.jpg/"}] ]]></data>
How can I get the same output in the second case?
or
Can I somehow convert the second output to be able to parse it with $.parseJSON ?
No problem with your script..
var xml = "<data>\
<![CDATA[ [{\"x\":0,\"y\":0,\"src\":\"images/image.jpg\"}] ]]>\
</data>";
var dataXML = $.parseXML(xml);
var json = $(dataXML).find('data').text();
console.log(json); // outputs [{"x":0,"y":0,"src":"images/image.jpg"}]
No error in this line too
var json = JSON.parse(json);
The problem could be about the browser, or the HTTP server reading the XML data and not automatically parsing it to be a JSON object due to the security reasons. Whatever the reason, this line is (by assuming automatic conversion) fails:
var json = $(dataXML).find('data').text();
Instead, change it with this:
var json = $.parseJSON($(dataXML).find('data').text()); // i think you can use $.parse() too.
This problem have occured to me a few times in various occasions on both platforms before, and I don't think a stable thing. Howeever, since there is no way that the browser (or JS interpreter) can "detect" that it's actually a JSON object (inside that XML), you must explicitly define it to be so, if you want to establish type safety of your stuff (which is a good programming method).
PS: "localhost" is very flexible about security, so I'd recommend not to rely on it very much :)