【问题标题】:Call post on external Rest API with Ajax使用 Ajax 在外部 Rest API 上调用 post
【发布时间】:2015-11-29 09:25:33
【问题描述】:

我是 Angular 的新手,我正在尝试调用 Rest API 并获得它的响应。我的问题是我的 JavaScript 一直卡在 Ajax 调用上。我不确定是我发送的数据还是 Ajax 调用的语法。我试图提醒“Hello world”并且它起作用了,然后我提醒 JSON 数组并且格式正确,但是当我发布 Ajax 帖子时,我根本没有得到任何响应。

任何见解都会很好,谢谢。

test.html

<button onclick="myFunction()">Post it</button>

test.js

function myFunction() {

    var postData = [{"logintype":"1","user":"Administrator","password":"12345","controlid":"999","host":"192.168.2.164"}
    ];

    $.ajax({
        url: '192.168.2.164/isapi/rip.dll/rest/session',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify( postData ), 
        success: function(){
           alert('hello');
        },
        error: function(){
            alert('error');
        }
    });
};

【问题讨论】:

  • 停止在应用程序上工作并开始阅读一些文档......您的示例与角度无关。
  • 你在用angularjs然后用docs.angularjs.org/api/ng/service/$httpservice
  • 定义“卡住”。成功功能会触发吗?错误函数会触发吗?您是否在开发者工具控制台中看到消息?您是否在 Developer Tools Net 选项卡中看到了请求?你看到那里的回应了吗?两者的格式都符合您的预期吗?
  • 这和角种子有什么关系?
  • 对不起,我的问题更具体了。

标签: javascript ajax post


【解决方案1】:

您指定了一个相对 URL,我认为您打算指定一个绝对 URL。如果当前页面 URL 是 http://localhost/myapp/,并且您请求 192.168.2.164/isapi/rip.dll/rest/session,则该 URL 被解析为 http://localhost/myapp/192.168.2.164/isapi/rip.dll/rest/session

如果192.168.2.164 是您尝试访问的服务器的 IP 地址(而不是相对于您服务器上当前路径的目录),您需要将 // 添加到 URL 的开头以使它是绝对的(嗯,至少与模式相关):

$.ajax({
    url: '//192.168.2.164/isapi/rip.dll/rest/session',
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify( postData ), 
    success: function(){
       alert('hello');
    },
    error: function(){
        alert('error');
    }
});

【讨论】:

    【解决方案2】:

    您的问题与角度无关。我将向您推荐的是有关如何执行 POST 请求的角度文档描述以及从文档中获取的语法的一个小示例。

    如果您想使用 Angular 进行开发,请学习使用 $http 或类似的东西。 https://docs.angularjs.org/api/ng/service/$http

    小例子:

    // Simple POST request example (passing data) :
    $http.post('/someUrl', {msg:'hello word!'}).
      then(function(response) {
        // this callback will be called asynchronously
        // when the response is available
      }, function(response) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
      });
    

    【讨论】:

      猜你喜欢
      • 2022-07-06
      • 1970-01-01
      • 2016-12-29
      • 1970-01-01
      • 2018-05-24
      • 1970-01-01
      • 2022-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多