【问题标题】:Unterminated string literal in JSON string with values from SQLServer with HTML tagsJSON 字符串中未终止的字符串文字,其值来自带有 HTML 标记的 SQLServer
【发布时间】:2013-03-27 21:44:54
【问题描述】:

我一直在尝试解决当我从该页面的下拉列表中选择“Breast”时在 Firebug 中遇到的“未终止的字符串文字错误” - http://wftp.whclpreview.com/search.html 并点击提交按钮。错误指向我以粗体突出显示的引号 -

SpecialGroups":"a","NationalAudits":"na","SpecialInterests":"

基本上,此错误是对 ASP.NET 函数的 $.ajax 调用的结果,该函数以 JSON 格式从 SQLServer 数据库(包含名为 SpecialInterests 的字段)返回数据。该数据库附加到管理员,允许用户通过 CKEDITOR 插件格式化文本。

如果文本很简单,则一切正常,但如果它包含任何 HTML 标记或换行符,则会出现上述错误。

欢迎提出任何建议,谢谢。

【问题讨论】:

  • 你对服务器端有控制权吗?
  • 是的,我执行接受数据表作为参数并输出有效 JSON 的函数如下 -
  • 那里可能有错误.. 为什么不使用 C# 库进行 JSON 字符串化?我敢肯定它们有很多,甚至可能在标准库中也有一个

标签: javascript html sql-server ajax json


【解决方案1】:

如果您使用 AJAX,您可以传递 Object Literal 或使用 de 数据构建查询字符串:例如

 //if the variable contains HTML string,
 //ensure to encode it before sending the request
 var note = "  <strong>Important:</strong><br/> Additional notes. ";
 note = encodeHtml(note);

 //Object Literal
 var params = { "date": date, "expiry": expiry, "priority": priority, "note": note };

 //Query string to append to the url
 var paramsUrl = buildUrlParams(params).join("&");

  $.ajax({
    type: "POST",
    url:  "myservice/client",

    //ugly way
    //data: "date="+date+"&expiry="+expiry+"&priority="+priority+"&note="+note,

    //passing data as Literal Object        
    data: params,

    //passing data as querystring
    //data: paramsUrl,

    success: function(data){ alert(data); }
  });

  //Creates an array of parameters to build an URL querystring
  //@obj: Object to build the array of parameters
  function buildUrlParams(obj) {
      return $.map(obj, function(value, key) {
          return key + "=" + value;
      });
  }

  //Encodes the HMTL to their respective HTML entities
  //@text: the HTML string to encode
  function encodeHtml(text) {
    var div = document.createElement("div");
    if ("innerText" in div) div.innerText = text;
    else div.textContent = text;
    return div.innerHTML.replace(/^\s+|\s+$/, "");
  }

【讨论】:

  • 根据 Explosion Pills 的建议,我决定使用 JSON.NET。而不是自定义功能,这是一种享受。非常感谢你们!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-01
  • 2013-10-16
  • 2014-06-09
  • 2014-06-14
  • 1970-01-01
相关资源
最近更新 更多