Getting type of response content from jQuery.Post

Is there a way to use jQuery.Post to find the type of response content?

I have a form in a modal window, and the idea is that if the form is invalid, the HTML fragment is sent, and the modality content is replaced with this fragment, if it is valid, I want a simple line with the contents for the flash notification (the type used here for SO).

I am currently testing if the returned string starts with "success", and if so, using the rest of the string as a flash notification. This is obviously a pretty hacky solution, and I really don't like it.

Ideally, I would like to have a conditional answer, and if it is "text / html", then insert the fragment, if it is "application / JSON", then I can not only send a message to the helper, but potentially other data (message, identifier, more a specific type of success / failure message, etc.) that would be useful for distribution to other forms in the future.

+3
source share
1 answer

jQuery already detects and converts the response based on the header of the content type (if on type>$.ajax() ). For example: if it finds "json"in the content header, it will be an object . You can simply do this:

$.post("myPage.html", { name: "value" }, function(data) {
  if(typeof(data) === "string") {
    //html
  } else {
    //JSON
  }
});

, JSON , :

$.post("myPage.html", { name: "value" }, function(data) {
  if(data.notification) {
    showMessage(data.notification);
  } else {
    //use the data object
  }
});
+6

Source: https://habr.com/ru/post/1772099/


All Articles