似乎无法成功使用jQuery ajax .get请求

时间:2018-06-28 13:59:27

标签: javascript jquery ajax

我有一台在本地运行的服务器(无需身份验证),当我使用终端对其执行GET /请求时,会得到一些JSON。现在,我想在我创建的网站上进行此操作。

<html>

<head>
    <link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.min.css'>  
    <meta charset="UTF-8">
</head>

<body>

    <div class="container">
        <h1>HTTP Request to server</h1>
        <div class="form-group">
            <label for="search-box"> URL: </label>
            <input id="search-box" type="text" class="form-control"/>
        </div>

        <button id="search-button" class="btn btn-primary"> Go </button>
        <hr />
        <p id="result"></p>
    </div>

    <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>

    <script>
        $(document).ready(function() {
            $('#search-button').click(function() {
                var url = $('#search-box').val();


                $.get(url, function(data) {
                    $("#result").append(data);
                },"json");

                //$("#result").text(url);
            });
        });
    </script>

</body>
</html>

我无法使用它,当我单击按钮时,什么也没有显示。

1 个答案:

答案 0 :(得分:-1)

如果服务器不允许与客户端共享资源,则无法直接从Javascript向服务器发送请求JSON的请求。

您将在浏览器的控制台面板中收到Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource.错误。

即使服务器允许资源共享,您也可以使用$.getgetJSON方法。