未捕获的ReferenceError:未定义请求,尝试解析JSON

时间:2017-07-19 00:10:25

标签: jquery html ajax

我试图找到以下代码的输出:

 <html>
    <body>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
            function request (){
                var URL = " http://jsonplaceholder.typicode.com/posts/1”;
                $.ajax({
                    type: "GET",
                    url: URL,
                    contentType: "application/json; charset=utf-8",
                    data: “{}”,
                    dataType: "jsonp",
                    success: function(msg) {
                        var json = msg; //NOTE since we said we’re getting back jsonp, jQuery did the parsing for us!
                        document.getElementById("current").innerHTML=json.title;
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                    document.getElementById("current").innerHTML = “Error fetching “ + URL;
                    }
                });
            }
        </script>
        <button type="button" onclick="request()"></button>
        <div id="output"></div>
    </body>
<html>

我写了最后的部分,按钮和div。我很好奇解析的JSON的输出是什么,但是当我试图通过它时我得到一个错误 - 函数&#34;请求&#34;没有定义。我认为它与src有关,但是我会相信我需要它,因为我没有本地的Jquery。我试着环顾四周,所有其他人遇到这个问题似乎做了完全不同的事情。我怎么写这个有什么问题吗?

提前致谢。

1 个答案:

答案 0 :(得分:0)

有很多错误:

  1. 使用事件监听器。
  2. 使用相同的<script>进行包含和嵌入。
  3. 使用就绪活动。
  4. 使用引用的JavaScript对象。
  5. 错误的引用。
  6. 混合使用JavaScript和jQuery。
  7. &#13;
    &#13;
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
      $(function () {
        $("button").click(function () {
          var URL = "http://jsonplaceholder.typicode.com/posts/1";    // 1
          $.ajax({
            type: "GET",
            url: URL,
            contentType: "application/json; charset=utf-8",
            data: {},    // 2
            // dataType: "jsonp",
            success: function(msg) {
              var json = msg; //NOTE since we said we’re getting back jsonp, jQuery did the parsing for us!
              $("#output").html(json.title);  // 3
            },
            error: function (xhr, ajaxOptions, thrownError) {
              $("#output").html("Error fetching " + URL);
            }
          });
        });
      });
    </script>
    <button type="button"></button>
    <div id="output"></div>
    &#13;
    &#13;
    &#13;