【问题标题】:jQuery ajax send json and return htmljQuery ajax 发送 json 并返回 html
【发布时间】:2020-04-01 05:03:16
【问题描述】:

我想执行一个带参数的 ajax 调用。如果可能的话,我想将参数作为 json 或文本发送。

结果以 html 内容类型返回。

这就是我尝试的方法

  var data2 = {
      'some-id': 5
  };

  $.ajax({
        type: "POST",
        url: /* some url */,
        data: JSON.stringify(data),
        dataType: 'json',
        success: function(data){      
            //some logic
        }
   }).fail(function() {
            //some error logic
   });

问题是,ajax 失败并显示“未定义”消息,因为它期望 html 作为响应,但是我的操作返回 html。

如何使它与 html 响应一起使用?

【问题讨论】:

  • "ajax 失败并显示消息 "undefined"" --- 什么输出该消息? PS:发送前不需要对js对象进行字符串化,很奇怪
  • $.ajax 直接在data参数中接受一个对象,内部转换成字符串,不需要手动吗?如果您收到 HTML,那将是服务器端问题!
  • 您的问题对我来说并不完全清楚。您是否需要告诉服务器只发送 html 作为答案?如果是这样,请在您的 ajax 调用中使用“接受”选项。
  • 这里 (api.jquery.com/jQuery.ajax) 表示设置“dataType”是“您期望从服务器返回的数据类型”。所以不会是:dataType:'html'。

标签: jquery


【解决方案1】:

只需将“dataType”设置为“html”即可。

参数“dataType”是jQuery ajax调用期望返回的类型。

更多信息:http://api.jquery.com/jQuery.ajax/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    • 1970-01-01
    • 2015-04-30
    • 1970-01-01
    • 2014-08-19
    相关资源
    最近更新 更多