简体   繁体   English

这是用JavaScript调用API的正确方法吗

[英]Is this the correct way to call an API in Javascript

I am quite new to javascript and calling APIs. 我对javascript和调用API很陌生。 Here is my code. 这是我的代码。 I am trying to call an API on apiary. 我正在尝试在养蜂场上调用API。

The API call is linked to an event listener (button click): API调用链接到事件侦听器(单击按钮):

$.lbl_sloganLabel.addEventListener('click', function(e) {
    // call api function
    if (Titanium.Network.online) {
        apiHelper.APIGetRequest('http://xxxxxxxx.apiary-mock.com/methodname', 
            function(e) {
                var status = this.status;
                if (status == 200) {
                    alert('works');
                }
            }, function(err) {      
                alert('Unknown error from api');
            }
        );
    } else {
        alert('No internet connection found');
    }
});

Currently if I make a request to googleAPI, I get a successful response (ie a connection is established), if I try to make a request to apiary ,it fails. 目前,如果我向googleAPI发出请求,则会收到成功的响应(即已建立连接),如果我尝试向apiary发出请求,则会失败。

I am not sure if this is the right way to do this, but from my understanding after the apiHelper has established a connection, I should be able to accessed the object as normal ie. 我不确定这是否是正确的方法,但是据我的理解,在apiHelper建立连接之后,我应该能够像平常一样访问对象。 .method name. 方法名称。

Anyway I need some clarification on this, cheers. 无论如何,我对此需要澄清。

您是否在Apiary中该API的设置中启用了CORS

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM