2017-07-19 74 views
-1

我试图找到下面的代码的输出:未捕获的ReferenceError:请求没有定义,试图解析JSON

<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> 

我写的最后部分,按钮和刻度。我很好奇经过解析的JSON的输出是什么,但是当我尝试运行它时发生错误 - 函数“request”没有被定义。我认为这与src有关,但我相信我需要那里,因为我本身没有Jquery。我试着环顾四周,其他所有人都看到这个问题完全不同。我是如何写这个的吗?

在此先感谢。

+0

'数据:“{}”,'是完全错误的......语法错误! –

+0

为了记录,我意识到ID标签不匹配 - 这似乎并没有影响我目前的问题。 –

+0

我解决了您的问题...查看解答的答案。 –

回答

0

有很多的错误:

  1. 使用事件侦听器。
  2. 使用相同的<script>进行包含和嵌入。
  3. 使用准备好的事件。
  4. 使用引用的JavaScript对象。
  5. 错误的引号。
  6. 混合JavaScript和jQuery。

<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>

+0

是的,那是有效的。谢谢。我想这只是我不了解jquery如何与按钮之类的东西进行交互。感谢快速回答! –

+0

@TylerRoman谢谢你接受答案。 –

相关问题