1

我想在用户单击按钮后加载一个 json 文件,但不知道该怎么做。

如果我直接加载文件,它将使用以下内容加载。

 <script src="data.json" type="text/javascript"></script>

但我希望用户在加载之前单击一个按钮,而不是在访问页面时加载。

谢谢

4

1 回答 1

2

Simple: use AJAX. It will load anything you want via Javascript which you can assign timings to. In this example we attach a click event to #myButton and when the event fires, we run a getJSON() call to the URL and handle the data accordingly.

HTML

<button id="myButton">Button</button>

Javascript (jQuery in my example)

$("#myButton").on('click', function() {
    $.getJSON("data.json", function(data) {
        //Handle my response
        alert(data);
    });
});

If you want an example not using jQuery then Google "Javascript AJAX".

于 2013-04-13T23:50:06.660 回答