【问题标题】:Jquery ajax fail when calling rest webservice调用rest webservice时Jquery ajax失败
【发布时间】:2014-11-18 13:27:18
【问题描述】:

我有一组 REST URI,我可以在服务器上进行身份验证后访问它们。该服务接受带有登录信息的 JSON 输入,并检索带有会话 ID 的 JSON 输出。

使用 Rest 客户端(如 chrome 扩展程序)时,一切正常。

现在我想使用 JS 实现它,但尽管返回失败,但我看不到任何错误的详细信息(错误消息为空白),也找不到我的代码中缺少的内容。

$.ajax({
    // the URL for the request
    url: "https://host002:50000/b1s/v1/Login",

    // the data to send (will be converted to a query string)
    data: {
        UserName: "manager",
        Password: "1234",
        CompanyDB: "CUS_001"
    },

    // whether this is a POST or GET request
    type: "POST",

    // the type of data we expect back
    dataType : "json",

    // code to run if the request succeeds;
    // the response is passed to the function
    success: function( json ) {
        $( "<h1/>" ).text( json.title ).appendTo( "body" );
        $( "<div class=\"content\"/>").html( json.html ).appendTo( "body" );
    },

    // code to run if the request fails; the raw request and
    // status codes are passed to the function
    error: function( xhr, status, errorThrown ) {
        alert( "Sorry, there was a problem! " + xhr.responseText);
        console.log( "Error: " + errorThrown );
        console.log( "Status: " + status );
        console.dir( xhr );
    },

    // code to run regardless of success or failure
    complete: function( xhr, status ) {
        alert( "The request is complete!" );
    }
});

xhr.responseText 始终为空白。状态总是错误的。 errorThrown 也总是空白。

我也尝试了 $post 方法,但得到了相同的行为。

【问题讨论】:

  • 可能是跨域限制。 REST 服务是您的吗?如果是这样,您是否启用了跨域请求?
  • 您的数据对象不是 JSON。
  • 我想过,但正如我所提到的,它可以在 Chrome/Firefox 上的 REST 客户端上运行。所以我认为不应该有跨域限制。是的,REST 服务在远程服务器上,在另一个域上。谢了!
  • 我相信它适用于扩展,因为权限是在清单中明确设置的。如果您使用像 Firebug 这样的检查器,响应标头无论如何都应该为您提供一些线索。
  • 我认为服务器返回了不正确的 JSON 响应,因为您的 ajax 请求使用 JSON 格式。

标签: javascript jquery ajax json rest


【解决方案1】:

您的 JSON 不正确。试试这个

data: JSON.stringify({UserName: "manager", Password: "1234", CompanyDB: "CUS_001"});

【讨论】:

  • 感谢您的意见。但这不是原因。更改后我遇到了同样的问题。
【解决方案2】:

从一个网址导航到另一个网址时,会弹出一个跨域错误。 尝试这样做。 使用 ajax 在您的同一个 url 上调用一个函数,并从那里使用 CURL 请求您的 Web 服务 url。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-06
    • 1970-01-01
    • 1970-01-01
    • 2019-03-31
    • 1970-01-01
    • 2012-09-23
    • 1970-01-01
    相关资源
    最近更新 更多