繁体   English   中英

AJAX JSON跨源读取阻止

[英]AJAX JSON Cross-Origin Read Blocking

我试图使我的代码正常工作,但是无论我在哪里或如何进行研究,我都无法找到解决问题的答案。

所以这是代码:

我试图从不同的资源,stackoverflow,jquery文档,json文档,关于跨域读取阻止(CORB)的不同google搜索中获取帮助

JSON格式

{
    "events" : [
    {
        "id" : "1", 
        "name" : "100m"
    },

    {
        "id" : "2", 
        "name" : "Long Jump"
    },

    {
        "id" : "3", 
        "name" : "Shot Put"
    },

    {
        "id" : "4", 
        "name" : "High Jump"
    }

]
}

的HTML

    <div class="container">
        <button id="getData">Events</button>
        <div id="eventList"></div>
    </div>

    <script>
        $(function () {
            $("#getData").click(function () {
                var eventList = $("#eventList");
                var url = "events.json";
                $.getJSON(url, function (data) {
                    var events = data.events.map(function (item) {
                        return item.id + " (" + item.name + ")";
                    });
                    eventList.empty();
                    if (events.length) {
                        var content = "<li>" + events.join("</li><li>") + "</li>";
                        var list = $("<ul>").html(content);
                        eventList.append(list);
                    }
                });
            });
        });
    </script>

我需要我的按钮才能使用AJAX起作用,但是当我按下按钮时,我遇到了“跨域读取阻止(CORB)阻止跨域响应”错误。

假设您将json结构发送到前端。 服务器端:您可以使用php将结构添加到数组,然后将其发送到前端。

服务器端可能类似于:

while("Loop through that file struture"){
  $output [] = array("id"=>$id,"name"=>$name);
}
echo json_encode($output);

客户端代码:

$.ajax({
   url : "documentlink.php", /*Link to the file, I assume you are getting that returned from a php.*/
   type: "post", /*If it is post use, else no need to use just remove it*/
   data:data, /*This if you want to send any parameter with your request to the server*/
   success:function(data){
     var obj = JSON.stringify(data);
     myObj = JSON.parse(obj);
     $.each(myObj, function(i){
          var id = myObj[i].id;
          var name = myObj[i].name;

    });
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM