在没有页面重新加载的情况下调用API

问题描述 投票:0回答:1

HTML

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <!-- jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <!-- Latest compiled JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Rokkitt" rel="stylesheet"> 
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" media="screen" href="styles1.css" />
    <script src="api.js"></script>
</head>

<body background="texture.jpg" class="bg">
    <div class="container">
        <h1> Awesome Quotes</h1>
        <p>Your daily dose of wisdom.</p>
        <div class="dynamic">
            <button class="btn btn-primary" id="button" type="submit">Get a New Quote</button>
        </div>
        <div class="quote"></div>
        <a href="https://twitter.com/intent/tweet?hashtags=quotes" target="_blank">
        <i class="fa fa-twitter"></i></a>
    </div>
</body>

</html>

JS

$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) {
  $(".quote").append(a[0].content + "<p>— " + a[0].title + "</p>")
});

这些是我的HTML和JS。我想要做的是在div中生成随机引用。我称之为API。每次我重新加载页面时都会出现随机引用。我需要做的就是点击“获取新报价”按钮并获取报价而无需使用jquery.Plus重新加载页面我需要单击twitter图标将我带到twitter,我在编辑器中已经看到相关报价,只是发布。

javascript jquery html api
1个回答
3
投票

HTML

为您的按钮提供课程,以便您轻松访问它

<button class="btn btn-primary getnewquote" id="button" type="submit">Get a New Quote</button>

脚本

var Res;
    $('.getnewquote').click(function(){
    //your ajax call
    $.ajax({
        type: "POST",
        url: "Your web service url",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (json) {
            Res = JSON.parse(json.d);
            $(".quote").append(Res[0].content + "<p>— " + Res[0].title + "</p>")


        },
        failure: function (msg) {
            console.log(msg);
        }
    });
    });
© www.soinside.com 2019 - 2024. All rights reserved.