Determining the Nature of a Server Response: JSON or Error Message
In the context of AJAX calls, it's often necessary to distinguish between JSON strings containing useful data and error messages from the server. While PHP's mysql_error() function produces error messages, the inability to parse a string as JSON indicates that it's likely an error message.
Solution: Leveraging JSON.parse()
To test if a string is valid JSON, we can utilize JSON.parse(). If the parsing operation succeeds, the string is considered JSON; otherwise, it's an error message.
Example Implementation
The following function, isJson(), implements this test:
function isJson(str) { try { JSON.parse(str); } catch (e) { return false; } return true; }
Usage
Now, it's easy to test the nature of a server response:
if (isJson(data)) { // Process JSON data } else { // Display error message alert(data); }
The above is the detailed content of How Can I Determine if a Server Response is JSON or an Error Message?. For more information, please follow other related articles on the PHP Chinese website!