【问题标题】:how to pass credentials for a webservice using jquery ajax call?如何使用 jquery ajax 调用传递 Web 服务的凭据?
【发布时间】:2013-01-12 19:42:26
【问题描述】:

我正在使用这样的 jquery ajax 调用:

$.ajax({
         url: WEBSERVICE_URL,
            type: "GET",
            dataType: "application/json; charset=utf-8",                   
            username: "admin",  // Most SAP web services require credentials
            password: "admin",
            processData: false,
            contentType: "application/json",
            success: function() {
               alert("success");
            },
            error: function() {
                   alert("ERROR");
                },
    });

仍然不会调用 Web 服务。每次我收到错误警报。有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: jquery ajax web-services web


    【解决方案1】:

    尝试使用 post 作为方法类型,大多数 web 服务都是安全的,需要使用 post 而不是 Get 传输

    加上帮助您调试错误和对错误的响应文本。

     $.ajax({
         url: WEBSERVICE_URL,
         type: "POST", //This is what you should chage
         dataType: "application/json; charset=utf-8",
         username: "admin", // Most SAP web services require credentials
         password: "admin",
         processData: false,
         contentType: "application/json",
         success: function () {
             alert("success");
         },
         error: function (xhr, ajaxOptions, thrownError) { //Add these parameters to display the required response
             alert(xhr.status);
             alert(xhr.responseText);
         },
     });
    

    【讨论】:

    【解决方案2】:

    如果你正在做跨域请求:

    $.ajax({
        url: "yoururl",
        type: "GET",
        dataType: 'json',
        xhrFields: {
             withCredentials: true
        }
    });
    

    【讨论】:

    • 请注意,一些嵌入式浏览器(如 Filemaker 中的 web 视图)会抑制用户/密码提示,因此这不适用于所有人。
    【解决方案3】:

    我的 2 美分。

    我在这个问题上浪费了大量时间,但我通过将请求的方法从 GET 更改为 POST 来解决它。

    奇怪的是,这两种方法类型 (GET/POST) 在通过 Postman 调用时都可以工作,但是当我将其更改为 POST 方法时,它才成功地访问了我的 Web API 端点。

    请注意,在我的例子中,我只是在使用 Windows 身份验证时传递了 grant_type,所以我在发布时没有传递用户名或密码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-24
      • 2015-03-07
      相关资源
      最近更新 更多