Home >Database >Mysql Tutorial >How Can I Determine if a Server Response is JSON or an Error Message?

How Can I Determine if a Server Response is JSON or an Error Message?

DDD
DDDOriginal
2024-12-02 19:12:13911browse

How Can I Determine if a Server Response is JSON or an Error Message?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn