我正在尝试使代码正常工作,但是无论我在哪里进行研究如何都找不到解决问题的方法。
所以这是代码:
我试图从不同的资源,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)阻止跨域响应”错误。
答案 0 :(得分:0)
假设您将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;
});
}
});