繁体   English   中英

如何在HTML页面中声明JS变量

[英]How to declare JS variable in HTML page

我有json文件来存储数字。 我也有JS文件来获取要以HTML显示的json数据。

作为手动显示的方式是在HTML代码下面的XXX中输入一个数字。 所以我希望数据是从后端动态获取的。

的HTML

<span id="num"> XXX </span> number of users

JS

$(document).ready(function() {

    var ajaxRequest;

    console.log();

    ajaxRequest= $.ajax({
        url: "result/total.json",
        type: "post",
        dataType: 'json',
        data: {'num':num},
    });
});

JSON格式

{
  "data": [
    {
      "num": "100"
    }
  ]
}

如果我的问题正确无误,那么您还想读取该JSON文件。 为此,您需要另一个从文件中获取数据的AJAX调用,并在成功回调中更改该范围的HTML。

这是一个简短的示例,说明您的回调应如何显示:

 $.ajax({
    url: "result/total.json",
    type: "get",
    dataType: 'json',
    success: function(data){
        //here you have access to your response object and you can use anything you want
        $("#num").html(data.responseText);
    }
});

如果您想要更好的版本,可以使用complete回调,以防呼叫失败。 这样,您还可以访问错误对象。

我通过编写此代码找到了答案。

$(document).ready(function() {

    var ajaxRequest;

    console.log();

    ajaxRequest= $.ajax({
        url: "result/total.json",
        type: "post",
        dataType: 'json',
        // data: {'num':num},

        success: function(data){
            console.log(data["data"][0]["num"]);
            //here you have access to your response object and you can use anything you want
            $("#num").html(data["data"][0]["num"]);
        }
    });    

});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM