【问题标题】:Ajax call not working when trying to send & return raw html尝试发送和返回原始 html 时,Ajax 调用不起作用
【发布时间】:2021-09-24 18:25:57
【问题描述】:

我正在使用 Ajax 调用来调用 C# 方法,该方法通过删除不需要的 html 标记和属性来处理用户粘贴输入。

当我使用 html 格式(标签和属性)粘贴内容时,我的 Ajax 调用不起作用。您能否建议如何为这种情况定义 Ajax 参数(将原始 html 发送到服务器端代码并​​返回原始 html)?

查看:

@(Html.Kendo().Editor()
 .Name("myEditor")
 .PasteCleanup(p => p.Custom("myPasteCleanUp")
)

脚本:

function myPasteCleanUp(input) {
      var response = null;
      if (input != null) {
       $.ajax({
         type: "POST",
         url: '/Home/htmlTagCleanUp',
         data: { userInput: input },
         async: false,
         success: function (response) {
            input = response;
         },
       });
     }
    return input;
   }

控制器:

[HttpPost]
[AllowAnonymous]
public ActionResult htmlTagCleanUp(string userInput)
{
  userInput = userInput;
  return Content(userInput, "text/html");
}

【问题讨论】:

  • 你能定义“不起作用”吗?正在发生什么,您有什么期待?
  • my Ajax call doesn't work 不是一个有用的描述。什么不起作用?而显示的代码你只有input = response;,那么你什么时候尝试使用input
  • 我的 ajax 调用链接到粘贴操作。当剪贴板的粘贴内容不包含 html 标签时,我的 htmlTagCleanUp() ActionResult 方法将被执行。当粘贴的内容确实包含 html 标记时,htmlTagCleanUp() 根本不会被调用/命中。响应应该包含服务器端处理的粘贴字符串。输入(响应)是返回到我的文本区域的内容。
  • 检查您的浏览器开发工具,了解请求会发生什么。
  • 您可能需要发布更多代码。我个人会 console.log ajax 数据,所以{ userInput: input } 以及成功响应,success: function (response) { input = response; console.log(response) } 还有你如何/在哪里初始化input

标签: html ajax model-view-controller actionresult contenttype


【解决方案1】:

原来缺少的部分是清理 HTML:

var  = document.createElement('div');
element.innerText = html;
var sanitizedHTML = element.innerHTML;

【讨论】:

    【解决方案2】:

    阻止您的 AJAX 调用的原因是您添加了 if 条件:

    if (html != null) {
    }
    

    你能告诉我 html 变量是在哪里定义的吗?尽管如此,我认为您正在尝试检查输入的空值,如果我们在它应该工作的条件下将 html 替换为 input 变量:

    if (input != null) {
    }
    

    【讨论】:

    • 我的错,我在粘贴代码时忘记重命名 html 变量 - 现在已更正。谢谢你的收获。上面列出了我自己对这个问题的回答。问候。
    【解决方案3】:

    我想问题是 MVC 认为带有标签的数据是一个错误的请求。

    因此建议您在控制器中的操作方法上方尝试:

    [ValidateInput(false)]
    

    【讨论】:

      【解决方案4】:

      看起来您需要将 [ValidateInput(false)] 属性添加到您的方法中,因为它可能会被视为 XSS 攻击。

      参考:ValidateInput(false) vs AllowHtml

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-21
        • 1970-01-01
        • 2018-09-10
        • 2018-07-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-17
        相关资源
        最近更新 更多