开发者

Getting the response content-type from jQuery.Post

Is there a way when using jQuery.Post to discover the content-type of the response?

I have a form in a modal window and the idea is that if the form is not valid then an HTML snippet is sent and the contents of the modal are replaced with this snippet, if it is valid I want a simple string with the content for a flash notification (of the type used here on SO).

Currently I am testing if the returned string begins with "success" and if so using the rest of the string as the flash notification. This is obvio开发者_C百科usly quite a hacky solution and I really don't like it.

Ideally I'd like to be able to have a conditional on the response and if it is "text/html" then insert the snippet, if it is "application/JSON" then I can not only send a message for the helper but potentially other data (message, id, more specific type of success/fail message etc) that would be helpful for extending to other forms in the future.


jQuery will already detect and convert the response based on the content type header (if no type is specified on the $.ajax() call). For example: if it finds "json" in the content-type header, it'll be an object. You can just do this:

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

Or, always pass back JSON, and have the notification message as a property on it, for example:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜