Ajax Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource

前端 未结 11 1509
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-02 16:55

I\'m writing a simple site that takes as input an idiom, and return its meaning(s) and example(s) from Oxford Dictionary. Here\'s my idea:

I send a request to the fol

相关标签:
11条回答
  • 2020-12-02 17:37

    Place below line at the top of the file which you are calling through AJAX.

    header("Access-Control-Allow-Origin: *");
    
    0 讨论(0)
  • 2020-12-02 17:39

    add these in php file where your ajax url call

    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Credentials: true ");
    header("Access-Control-Allow-Methods: OPTIONS, GET, POST");
    header("Access-Control-Allow-Headers: Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control");
    
    0 讨论(0)
  • 2020-12-02 17:44

    I used the header("Access-Control-Allow-Origin: *"); method but still received the CORS error. It turns out that the PHP script that was being requested had an error in it (I had forgotten to add a period (.) when concatenating two variables). Once I fixed that typo, it worked!

    So, It seems that the remote script being called cannot have errors within it.

    0 讨论(0)
  • 2020-12-02 17:45

    We can not get the data from third party website without jsonp.

    You can use the php function for fetch data like file_get_contents() or CURL etc.

    Then you can use the PHP url with your ajax code.

    <input id="idiom" type="text" name="" value="" placeholder="Enter your idiom here">
    <br>
    <button id="submit" type="">Submit</button>
    <script type="text/javascript">
    $(document).ready(function(){
        $("#submit").bind('click',function(){
            var idiom=$("#idiom").val();
            $.ajax({
                type: "GET",
                url: 'get_data.php',
                data:{q:idiom},
                async:true,
                crossDomain:true,
                success: function(data, status, xhr) {
                    alert(xhr.getResponseHeader('Location'));
                }
            });
    
        });
    });
    </script>
    

    Create a PHP file = get_data.php

    <?php
      echo file_get_contents("http://www.oxfordlearnersdictionaries.com/search/english/direct/");
    ?>
    
    0 讨论(0)
  • 2020-12-02 17:47

    This also need.

    <?php
    header("Access-Control-Allow-Origin: *");
    
    0 讨论(0)
提交回复
热议问题