如何使用 ajax 触发 jenkins 作业构建?

how to use ajax to trigger jenkins job build?

我正在编写一个网页,让其他人可以使用 jenkins 中的参数触发一些作业的构建。所以我使用 ajax 发送 POST 请求:

var urlString = "http://localhost:8080/job/myjob/buildWithParameters";

$.post(
    urlString,
    {myParam:"there is some data"},
    function(data)
    {
        alert(data);
    },
    "json"
);

但我收到了 Http 403 响应:

XMLHttpRequest cannot load http://localhost:8080/job/myjob/buildWithParameters. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 403.

我知道跨站问题,但是我无法从 Google 中搜索到任何有用的信息,ajax 可以完成这项工作吗?

更新: 我找到了 similar question

所以我将代码更新为:

$.ajax({                              
    type: "POST",
    url: urlString,
    dataType: 'jsonp',
    data: {},
    beforeSend: function(xhr){
        xhr.setRequestHeader("Authorization", "Basic " + btoa("admin:123456"));
    },
    success: function(data) {
    },             
    complete: function(xhr, statusText){
    }                                                                 
});

我可以确认用户名和密码是正确的,但我得到了 405 Method Not Allowed。有什么问题吗?

Jenkins 想要 POST 而不是 GET HTTP 请求,JSONP 请求是 GET:你不能那样做 :D

你可以尝试这样做:

  1. 使用 AJP 绑定启动 jenkins here

  2. 将 Apache2 httpd 配置为 reverse proxy for the Jenkins AJP

  3. 在 Apache2 响应中强制 header 如所述 here 以启用 CORS

最后可以直接使用POST代替JSONP

享受 XSS 的乐趣 :D

将您的网页放在 $JENKINS_HOME 目录下的 userContent 文件夹中。然后在浏览器中打开 $JENKINS_URL/userContent/yourwebpage.html。现在页面中的 javascript 是从 ajax 调用所在的相同来源加载的,因此应该允许它没有 CORS 技巧。