当参数包含 html 标记时,Ajax 调用失败

Ajax call fail when parameter contain html tag

本文关键字:Ajax 调用 失败 参数 包含 html      更新时间:2023-09-26

我有这个ajax:

 $.ajax({
      url: '/PostComment/AddComment',
      type: 'POST',
      dataType: 'json',
      cache: false,
      data: { "PostId": PostId, "CommentText": CommentText },
      success: function (data){
           alert('Ok');
      }
 });

问题是当 CommentText 变量包含任何 html 标记时,ajax 调用会失败。我知道这是一个奇怪的问题,但这就是发生的事情。

尝试将编码值发送到服务器端:

commentText = encodeURIComponent(commentText);

在服务器端,如果您使用的是Java,那么您可以执行以下操作:

String commentStr = URLDecoder.decode(request.getParameter("commentText"), "UTF-8");

在javascript中:

JSON.stringify(CommentText));

请参阅:在 JSON 中放置 HTML 时必须做的 4 件事