使用Ajax在外部Rest API上调用post

Call post on external Rest API with Ajax

本文关键字:调用 post API Rest Ajax 外部 使用      更新时间:2023-09-26

我是angular的新手,我正在尝试调用Rest API并获得其响应。我的问题是我的JavaScript一直卡在Ajax调用上。我不确定这是我发送的数据还是Ajax调用的语法。我试图提醒'Hello world',这是有效的,然后我提醒JSON数组,格式正确,但当我做Ajax的帖子,我没有得到任何响应。

任何见解都很好,谢谢。

test.html

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

. 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');
        }
    });
};

您指定了一个相对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');
    }
});

你的问题与angular无关。我要让你参考的是angular文档中关于如何执行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.
  });