While making AJAX calls, it can be challenging to distinguish between valid JSON responses and error messages returned from the server. To address this issue, you may consider creating a function called isJSON() that allows you to test whether a given response is indeed a JSON string.
A straightforward approach to determine if a string is JSON is to utilize the JSON.parse() method. This method attempts to convert the string into a JavaScript object. If the conversion is successful, it indicates that the string is valid JSON; otherwise, it throws an exception.
Here's how you can implement the isJSON() function:
function isJSON(str) { try { JSON.parse(str); } catch (e) { return false; } return true; }
With the isJSON() function at your disposal, you can now easily test your AJAX response:
if (isJSON(data)) { // Handle JSON data } else { // Handle error message alert(data); }
This approach enables you to determine the nature of the response returned by the server and handle it accordingly, allowing you to build robust and responsive AJAX applications.
The above is the detailed content of How Can I Reliably Determine if an AJAX Response is Valid JSON?. For more information, please follow other related articles on the PHP Chinese website!