gpt4 book ai didi

javascript - 可以通过浏览器访问远程 json 组件,但不能通过 $.getJSON() 以编程方式访问

转载 作者:行者123 更新时间:2023-11-30 05:43:49 27 4
gpt4 key购买 nike

我已经为解决这个问题奋斗了 3 天,但遇到了“谷歌重载”问题 - 希望得到一些帮助。

我们在 http://jenkinsBuild.mycompany.com:8080 上有一个 Jenkins 构建服务器所以如果我在浏览器中输入这个 url...

http://jenkinsBuild.mycompany.com:8080/view/my_view/job/build_me/123/api/json?tree=result

...浏览器页面返回显示...

{"result":"SUCCESS"}

现在,根据Jenkins Wiki ,“Jenkins 为其功能提供机器可使用的远程访问 API”通过 REST API 支持 json 和 jsonp,我认为这应该可以规避任何同源策略问题。

我正在尝试(使用最新的 Chrome 浏览器)获取相同的 json 组件 {"result":"SUCCESS"} .

我正在使用带有 $.getJSON() 的 HTML/javascript如下所述调用。 HTML 文件目前驻留在我的本地计算机上,但最终可能会存在于 wiki 上。代码后列出了三个 url 的控制台输出。

如何通过直接在浏览器中输入 url 获得相同的 json 结果?感谢您的帮助。

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var url1 = "http://jenkinsBuild.mycompany.com:8080/view/my_view/job/build_me/123/api/json?tree=result";
var url2 = "http://jenkinsBuild.mycompany.com:8080/view/my_view/job/build_me/123/api/json?tree=result&callback=?";
var url3 = "http://jenkinsBuild.mycompany.com:8080/view/my_view/job/build_me/123/api/json?callback=?&tree=result";

$('button').click(function(){
$.getJSON(url1, function(json) {
$("#reply").append("got callback: " + json);
});
});
});
</script>

</head>
<body>

<button>Get Jenkins</button><br />

<div id="reply">

</div>

</body></html>

三个 URL 的控制台输出...

url1 -> XMLHttpRequest cannot load <a href="http://jenkinsBuild.mycompany.com:8080/view/my_view/job/build_me/123/api/json?tree=result" rel="noreferrer noopener nofollow">http://jenkinsBuild.mycompany.com:8080/view/my_view/job/build_me/123/api/json?tree=result</a>. Origin null is not allowed by Access-Control-Allow-Origin.

url2 -> Uncaught SyntaxError: Unexpected token : json:1

url3 -> Uncaught SyntaxError: Unexpected token : json:1

最佳答案

更新:

Url1 不是有效的 jsonp 调用,因为它没有指定回调。不确定为什么 url2 和 url3 失败。

这是另一种尝试手动指定回调函数名称的方法:

var url2 = "http://jenkinsBuild.mycompany.com:8080/view/my_view/job/build_me/123/api/json?tree=result&callback=my_local_javascript_function";

其中 my_local_javascript_function 是调用浏览器上 javascript 代码中的一个函数。将发生的是服务器将使用如下所示的脚本进行响应:

my_local_javascript_function({ //json object in here });

该函数需要在您的本地浏览器上可用,然后才会运行。有关 JSONP 的更多信息,请参阅此处:http://en.wikipedia.org/wiki/JSONP

关于javascript - 可以通过浏览器访问远程 json 组件,但不能通过 $.getJSON() 以编程方式访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19199270/

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