JavaScript - 动态脚本标记导致“意外令牌非法”

时间:2015-07-15 22:44:18

标签: javascript jquery json json-ld

我在动态生成此脚本标记时遇到错误。它似乎不喜欢开放式支架。有人可以帮忙吗?

$(document).ready(function(){

  (function(callback){
    var s = document.createElement('script');
    s.setAttribute('type', 'application/ld+json');

    s.text = '{
      "@@context": "http://schema.org",
      "@@type": "Person",
      "name": "John Doe",
      "jobTitle": "Graduate research assistant",
      "affiliation": "University of Dreams",
      "additionalName": "Johnny",
      "url": "http://www.example.com",
      "address": {
        "@@type": "PostalAddress",
        "streetAddress": "1234 Peach Drive",
        "addressLocality": "Wonderland",
        "addressRegion": "Georgia"
      }
    }';
    s.onload = callback;
    document.body.appendChild(s);
  })();

})



</script>

1 个答案:

答案 0 :(得分:4)

JavaScript不允许使用多行字符串文字,因此s.text = '行的语法无效。

如果您将纯JSON输出到您的脚本,那么您可以这样做,使其成为一个字符串:

s.text = JSON.stringify({
  "@@context": "http://schema.org",
  "@@type": "Person",
  "name": "John Doe",
  "jobTitle": "Graduate research assistant",
  "affiliation": "University of Dreams",
  "additionalName": "Johnny",
  "url": "http://www.example.com",
  "address": {
    "@@type": "PostalAddress",
    "streetAddress": "1234 Peach Drive",
    "addressLocality": "Wonderland",
    "addressRegion": "Georgia"
  }
});