【问题标题】:.js files and the jQuery AJAX Method.js 文件和 jQuery AJAX 方法
【发布时间】:2015-10-22 08:02:18
【问题描述】:

如果我有以下 .js 文件,如何使用 jQuery AJAX 方法调用它?我熟悉使用 JSON 文件,但这既是 .js 文件,又与 JSON 文件具有相似的语法,所以让我感到困惑。 JSON.stringify() 方法是解决方案的一部分吗?虽然这只是示例代码,但我最终会尝试根据年龄创建单独的数组,但这不应该影响原始问题。

these_records = [
  {
    "name": "sarah",
    "age": "50"
  },
  {
    "name": "mary",
    "age": "40"
  }
]

【问题讨论】:

    标签: javascript jquery ajax json stringify


    【解决方案1】:

    不需要 jQuery。不需要阿贾克斯。只需加载并使用它。

    <script src="records.js"></script>
    <script>
        alert(these_records[0].name);
    </script>
    

    【讨论】:

    • 谢谢你,但就像 Plummer 提到的那样,我正在使用临时模型数据,所以我想使用 AJAX 调用。
    【解决方案2】:

    通常,您这样做的唯一原因是您使用临时模型数据代替 API 服务。

    您应该仍然可以通过 AJAX 访问文件的内容。

    $.ajax({
      url: "path/to/file.js",
      dataType: "script",
      success: function(data){
        console.log(data.name);
      }
    });
    

    甚至可以通过$.getScript():

    $.getScript("path/to/file.js", function( data ) {
      console.log(data.name); 
    });
    

    此外,您不需要将数组定义为变量。如果要返回多个结构,作为嵌套数组会更好。

    { 
      'these_records' : { 
        { 
          "name": "sarah",
          "age": "50" 
        },
        { 
          "name": "mary",
          "age": "40" 
        }
      }
      "other_records": {
        { 
          "name": "bob",
          "age": "50" 
        },
        { 
          "name": "bobert",
          "age": "40" 
        }
      }
    }
    

    【讨论】:

    • 第一个我得到了最后一个“)”的意外令牌
    • 缺少大括号。立即尝试。
    猜你喜欢
    • 2012-05-16
    • 1970-01-01
    • 2015-12-16
    • 2011-08-04
    • 2015-04-23
    • 1970-01-01
    • 2016-01-09
    • 2011-02-05
    • 2013-12-25
    相关资源
    最近更新 更多