gpt4 book ai didi

javascript - 无法解析 url 中的 json

转载 作者:行者123 更新时间:2023-11-28 01:14:16 28 4
gpt4 key购买 nike

<html>
<body>
<script src='http://code.jquery.com/jquery-1.10.2.min.js'></script>
<script>
$(document).ready(function () {
$.ajax({
type: 'GET',
async: false,
contentType: "application/json",
url: "http://www.XXX.XXX.in/api/categories",//url:"dir/categories",
dataType: "jsonp", //dataType: "jsonp",
success: function (data) {
$.each(data, function(i,data) {
var det="<div>id :"+data.categoryId+" Name "+ data.categoryName+"</div></br>";
$(det).appendTo("#display");

//alert(det);
});
alert(data);
},
error: function (data) {
alert("this is error "+data);
}
});
});

</script>

<div id="display"></div>
</body>
</html>

在上面的代码中,我尝试访问类别 json 并打印详细信息。
我通过两种方式做到这一点:

我已将类别文件保存在 dir/文件夹中并访问它,这可以正确显示结果。
当我尝试在线访问它时,出现错误:当我给出 dataType:"json" 而不是 jsonp 时,我给出以下错误:

OPTIONS http:// XXX.XXX.in/api/categories 404 (Not Found)
XMLHttpRequest cannot load http:// XXX.XXX.in/api/categories. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http:// localhost:8080' is therefore not allowed access.

我不知道服务器是否有跨平台引用。添加。

最佳答案

您无法使用 JAVASCRIPT 从您的域访问其他域的数据。这是一条名为“Same origin Policy”的安全规则

因此,要获取另一个域的数据,您可以编写服务器端脚本(可能是 PHP 或您熟悉的其他语言。),然后您可以从脚本向服务器发出 ajax 请求。

浏览器强制执行同源策略,以保护网站免受其他网站发出 xhr 请求并像显示自己的内容一样显示其内容。

因此站点 A.com 无法使用 XHR 连接到 B.com,或者:
http://A.com无法连接到http://sub.A.com
localhost:80 无法连接到 localhost:8080

编辑

根据您的要求,这里是使用 PHP 脚本的解决方案。

get_json_from_url.php

<?php
header("Content-type: text/json");
$response = fopen('http://www.eazydial.logicengine.in/api/categories', "rb");
echo stream_get_contents($response);
?>

HTML 页面

<html>
<body>
<script src='http://code.jquery.com/jquery-1.10.2.min.js'></script>
<script>
$(document).ready(function () {
$.ajax({
type: 'GET',
url: "get_json_from_url.php",
dataType: "json",
success: function (data) {
$.each(data, function(i,data) {
var det="<div>id :"+data.categoryId+" Name "+ data.categoryName+"</div></br>";
$(det).appendTo("#display");

});
console.log(data); //alert can't print [object] so always use console.log() to inspect object and it values. (see output in browser console)
},
error: function (data) {
console.log("Err:");
console.log(data);
}
});
});

</script>

<div id="display"></div>
</body>
</html>

此处以 PHP 脚本提供的解决方案仅适用于 GET 请求方法。如果您想对任何 API 使用 POST 请求,请查找 cURL library从 api 获取数据。

关于javascript - 无法解析 url 中的 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24030869/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com