M
M
My joy2016-01-17 23:56:00
JavaScript
My joy, 2016-01-17 23:56:00

Javascript parsing incoming JSON?

Good evening comrades.
When sending json from php to js I use JSON.parse(response). And here's what seems strange to me:
If php sends with standard headers (text / html), then the JSON.parse () function works correctly. If I forcibly change the headers to application/json, then the parsing crashes with the [Object object] blob exception, this indicates that the incoming data does not need to be parsed, and is already a ready-made object. Do I understand everything correctly, and is this rule valid for all browsers that if the data comes with the application/json header, then it is not necessary to run it through JSON.parse?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nazar Mokrinsky, 2016-01-18
@t-alexashka

Depends on how you are making the request. If it's jQuery, then it's fine. If XHR2 - there is an opportunity to pick up both the raw answer and the parsed one. Show code :)

M
My joy, 2016-01-18
@t-alexashka

yes, jekvery.

$('.as-ajax').submit(function(e){
    
    e.preventDefault();
    
    $.post($(this).attr('action'), $(this).serialize(), function(response) {
      
      try {
        var response = JSON.parse(response);
      }
      catch (e) {
        var response = {
          status: 400,
          message: 'Unknown error occurred: [' + response + ']'
        };
      }
      
      sys.noty(response.message, response.status > 200 ? 'error' : 'success');
      
    });
  
  });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question