Ajax请求url和div中的显示响应不起作用?

jav*_*016 1 javascript ajax jquery

我正在尝试向网站提出ajax请求,并仅显示其中的一部分。我的代码不起作用,我也看不出原因。另外,如何解析对象并仅显示对象的一部分(只是一个属性)?非常感谢!

JS:

  $(document).ready(function(){
   $('#buttonClick').on('click', 'button',function(){
    $.ajax('http://ShakeItSpeare.com/api/sentence', {
     success: function(response){
      console.log(response)
   //console.log of response works 
        $('.screen').html(response).fadeIn();
      }
    })
  });
});
Run Code Online (Sandbox Code Playgroud)

的HTML

<body>
    <div id="buttonClick">
<button>click Me</button>
<ul class="screen"></ul>
    </div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

<script type="text/javascript" src="shakes.js"></script>
</body>
Run Code Online (Sandbox Code Playgroud)

Ste*_*mez 5

将您要插入的JSON属性名称添加到HTML中应仅插入该值。例如,在下面的代码中,我在“ response.sentence”中添加了“ sentence”属性。

$(document).ready(function(){
  $('#buttonClick').on('click', 'button',function(){
    $.ajax('http://ShakeItSpeare.com/api/sentence', {
     success: function(response){
        console.log(response)
        //changed original code from ".html(response)" to ".html(response.sentence)"
        $('.screen').html(response.sentence).fadeIn();
      }
    })
  });
});
Run Code Online (Sandbox Code Playgroud)

工作代码笔:工作代码笔

  • 提到您将.html()更改为.text()会给新用户以.html()错误的印象,这是不正确的。它们是不同的,但是两者都可以使用。为了清楚起见,您可能会失去一点点:) (2认同)