得到响应内容类型从jQuery.Post类型、内容、Post、jQuery

2023-09-10 16:54:31 作者:提笔书几行

有没有办法使用jQuery.Post来发现内容类型响应的时候?

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

我有一个模式窗口的一种形式,这个想法是,如果表单无效,则HTML片段发送和模式的内容被替换为这个片段,如果它是有效我想要一个简单的字符串(这里使用上,这样类型)的闪存通知的内容。

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 obviously quite a hacky solution and I really don't like it.

在理想情况下,我想能够有一个有条件的响应,如果它是text / html,那就插入片段,如果是应用/ JSON的,那么我不仅可以发送消息的辅助但潜在的其他数据(消息,标识,成功的更具体的类型/失败消息等),这将是有帮助的,在将来扩展到其它形式的

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将已经的检测和转换基于​​内容类型头响应(如果没有键入上的 $。阿贾克斯() 调用)。例如:如果找到JSON在content-type标题,这将是一个对象。你可以这样做:

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
  }
});

或者总是的回传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
  }
});