如何從 JavaScript 讀取腳本標籤中的 JSON? - How can I read a JSON in the script-tag from JavaScript?

問題:

I have a dynamically generated page where I want to use a static JavaScript and pass it a JSON string as a parameter.我有一個動態生成的頁面,我想在其中使用靜態 JavaScript 並將 JSON 字符串作爲參數傳遞給它。 I have seen this approach used by Google (see Google's +1 Button: How do they do it? ).我已經看到 Google 使用的這種方法(請參閱Google 的 +1 按鈕:他們是如何做到的? )。

But how should I read the JSON string from the JavaScript?但是我應該如何從 JavaScript 中讀取 JSON 字符串?

<html>
  <head>
    <script src="jquery-1.6.2.min.js"></script>
    <script src="myscript.js">{"org": 10, "items":["one","two"]}</script>
  </head>
  <body>
    Hello
  </body>
</html>

In this JavaScript I would like to use the JSON argument {"org": 10, "items":["one","two"]} from the HTML document.在此 JavaScript 中,我想使用 HTML 文檔中的 JSON 參數{"org": 10, "items":["one","two"]} I don't know if it's best to do it with jQuery or without.我不知道最好用 jQuery 還是不用 jQuery。

$(function() {
    // read JSON

    alert("the json is:")
})

解決方案:

參考: https://stackoom.com/en/question/VoCL
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章