I'm calling to the server using jQuery's $.post method and assigning the JSON response to a variable called "result". The response is an array in PHP's json_encode() function.
Up until now I've always just used the properties of "result" directly, as the JSON gets parsed into an object automatically. But now, after some debugging, I've found that my code only works when I use JSON.parse(result) first.
What could've caused this sudden change?
Solution: Adding header("Content-Type: application/json") serverside when echoing a JSON encoded response.
CodePudding user response:
Either:
- Your server stopped setting the correct
Content-Typeresponse header (application/json). PHP will claim anything it sends to the browser istext/htmlunless you use theheader()function to override that. - You didn't say
type: 'json'to make jQuery (a) set anAcceptheader and (more relevantly) (b) ignore the response'sContent-Typeheader and try to parse it as JSON regardless.
