首页 > 解决方案 > 无法让 .getJSON 触发 onclick

问题描述

我正在尝试让“restapp”功能触发 onclick,但它似乎不起作用。我不确定问题是什么。有什么建议么?

这是我的代码:

<html>
<head>
  <title>Restaurant App</title>
</head>
<body>

<input id="info" type="button" onclick="restapp()" value="Create Table From JSON">

<hr>
<pre id="demo"></pre>

<script>
result = [];
city = 'chicago';
opURL = 'http://opentable.herokuapp.com/api/restaurants?city=' + city;

function restapp() {
    $.getJSON(opURL, function(data) {
        //data is the JSON string
        for (i=0; i<data.restaurants.length; i++) {
            result.push("Name: " + 
            data.restaurants[i].name);
                result.push("Address: " + 
            data.restaurants[i].address);
                result.push("Price: " + 
            data.restaurants[i].price);
                result.push("<br>");
            }
        document.getElementById("demo").innerHTML = JSON.stringify(result, null, 2);
    });
}

</script>

</body>
</html>

标签: javascripthtmljsononclick

解决方案


你在哪里JQuery

$.getJSON 需要 JQuery。检查您的浏览器控制台是否有错误。

<script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>

将此插入您的head标签中。

您可以使用 JQuery 选择器来选择您的输入字段并使用 click 方法进行点击事件。


推荐阅读