使用 Json 文件时出现“jQuery 模板”问题

使用 Json 文件时,我遇到了“jQuery 模板”的问题。当我使用下面的代码时,我没有错误,但是它不起作用。


当我将数据 Json 的内容定义为变量时,问题就解决了。但是每当我尝试使用 Json 文件时,它都不起作用


我对此感到非常兴奋,但没有找到任何东西。请指导我。


  <script type="text/javascript">

    $(function() {

      jQuery.getJSON("js/data.json", function(myData) {

        $("#ourTemplate").tmpl(myData).appendTo("#tableContent");


      });



    })

  </script>

  <script id="ourTemplate" type="text/x-jquery-tmpl">

    <tr>

      <td>${username}</td>

      <td>${name}</td>

      <td>${skills}</td>

      <td>${age}</td>

    </tr>

  </script>

<!DOCTYPE html>

<html dir="ltr">

<title>jQuery templates</title>


<head>


  <script src="https://code.jquery.com/jquery-3.4.1.min.js" charset="utf-8"></script>

  <script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js" charset="utf-8"></script>



</head>


<body>

  <table border="1">

    <thead>

      <th>username</th>

      <th>name</th>

      <th>skills</th>

      <th>age</th>

    </thead>

    <tbody id="tableContent">


    </tbody>

  </table>

</body>


</html>


慕村9548890
浏览 116回答 1
1回答

慕少森

当我将数据Json的内容定义为变量时,问题就解决了那是因为您的“JSON”实际上并不是 JSON;它只是一个普通的 JavaScript 对象。将 JSON 文件的内容更改为以下内容,它将起作用(注意键名周围的引号):[&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; "name": "milad",&nbsp; &nbsp; &nbsp; &nbsp; "username": "mldv404",&nbsp; &nbsp; &nbsp; &nbsp; "skills": "php , javascript , css , jQuery",&nbsp; &nbsp; &nbsp; &nbsp; "age": 24&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; "name": "hamid",&nbsp; &nbsp; &nbsp; &nbsp; "username": "hamidJ",&nbsp; &nbsp; &nbsp; &nbsp; "skills": "Mysql , javascript , css , jQuery",&nbsp; &nbsp; &nbsp; &nbsp; "age": 25&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; "name": "hossein",&nbsp; &nbsp; &nbsp; &nbsp; "username": "hosseindavari",&nbsp; &nbsp; &nbsp; &nbsp; "skills": "java , simpless , document , jQuery",&nbsp; &nbsp; &nbsp; &nbsp; "age": 34&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; "name": "davood",&nbsp; &nbsp; &nbsp; &nbsp; "username": "davoodSun",&nbsp; &nbsp; &nbsp; &nbsp; "skills": "visial Basic , dot net7 , c++ , jQuery",&nbsp; &nbsp; &nbsp; &nbsp; "age": 24&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; "name": "zahra",&nbsp; &nbsp; &nbsp; &nbsp; "username": "sunMedia",&nbsp; &nbsp; &nbsp; &nbsp; "skills": "python , hibernate , AJax , PostgerSql",&nbsp; &nbsp; &nbsp; &nbsp; "age": 24&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; "name": "mohsen",&nbsp; &nbsp; &nbsp; &nbsp; "username": "msnv",&nbsp; &nbsp; &nbsp; &nbsp; "skills": "vbScript , php , javascript , jQuery",&nbsp; &nbsp; &nbsp; &nbsp; "age": 24&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; "name": "mahdi",&nbsp; &nbsp; &nbsp; &nbsp; "username": "mhdi23",&nbsp; &nbsp; &nbsp; &nbsp; "skills": "php , javascript , css , jQuery",&nbsp; &nbsp; &nbsp; &nbsp; "age": 24&nbsp; &nbsp; }]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript