JavaScript - 导致 "unexpected token illegal" 的动态脚本标记

JavaScript - Dynamic Script tag causing "unexpected token illegal"

我在动态生成此脚本标记时遇到错误。它似乎不喜欢左括号。有人可以帮忙吗?

$(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>

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"
  }
});