2013-10-20 43 views
1

我有一些简单的JavaScript函数与像这样的一个API互动登录:如何初始参数传递给JavaScript函数

login: function(username, password) { 
    var calledUrl = baseapi + "user/login/" + credentials; 
    calledUrl.post(
     function (content) { 
      /*console.log("success" + JSON.stringify(content, null, 4));*/ 
     }, 
     function (e) { 
      console.log("it failed! -> " + e); 
     }, 
     { 
      "username": username, 
      "password": password 

     }, 
     {"Accept" : "application/json"} 
    ); 
}, 

的问题是,在URL我必须通过一些证书,他们看起来这样的:

var credentials = "?api_username=" + api_username + "&api_key=" + api_key; 

现在这个变量是硬编码进行一些测试,但它当然应该使用功能每个人改变。我不想在每次请求时都要求它,在这种情况下,我只想询问usernamepassword。我想在初始化过程中或者在调用它时调用它,然后在执行各种函数时记住它。

+1

我不明白,究竟是什么问题与您的代码? –

+0

对不起,如果它不是很清楚,代码的作品,但有一个硬​​编码的参数,API的凭据。我有更多的这些功能,他们每个人都使用这个参数。我希望能够在通话中记住这个参数,所以我不必一直输入。 – Bastian

回答

1

如果.login()是通常所需要的凭据第一种方法,那么你可以让该方法所需的参数,然后存储在对象中的凭证:

login: function(username, password, credentials) { 
    // save credentials for use in other methods  
    this.credentials = credentials; 
    var calledUrl = baseapi + "user/login/" + credentials; 
    calledUrl.post(
     function (content) { 
      /*console.log("success" + JSON.stringify(content, null, 4));*/ 
     }, 
     function (e) { 
      console.log("it failed! -> " + e); 
     }, 
     { 
      "username": username, 
      "password": password 

     }, 
     {"Accept" : "application/json"} 
    ); 
}, 

然后,在其他的方法,您可以通过this.credentials访问此用户的凭据。

如果还有其他方法也可以先调用并需要它们的凭据,那么您可以为这些凭证作为参数,或者您可以创建一个只建立凭据的方法,或者可以创建它是这个对象的构造函数中的一个参数。


你可能还必须解决这一行:

calledUrl.post(...) 

因为calledUrl是一个字符串,字符串没有.post()方法,除非你正在使用某种形式的第三方库的那增加一个。

+0

calledUrl.post($ – jacouh

+0

@jacouh - ?我不知道这事 - 这仅仅是OP的代码,我不认为这个问题的操作部分,虽然它看起来很奇怪,也许错 – jfriend00

+0

是在calledUrl .POST确实奇怪,它来自名为'abaaso'。 – Bastian

1

我建议您阅读JavaScript中的范围。没有更多的解释你想做什么,我会尝试像这种模式...

var app = { 
    baseapi: 'http://some.url.com' 

    /* assuming the api user/pass are different form the account trying to log in */ 
    ,api_username: '' 
    ,api_key: '' 

    ,username: '' 
    ,userpass: '' 

    ,get_creditialString: function() { 
    return '?api_username=' + this.api_username + '&api_key=' + this.api_key; 
    } 
    ,init: function(){  
    // do something to prompt for username and password 
    this.username = 'myUserName'; 
    this.userpass = 'supersecretpassword'; 

    this.login(); 
    } 
    ,login: function() { 
    var calledUrl = this.baseapi + "user/login/" + this.get_credentialString(); 
    calledUrl.post(
     function (content) { 
      /*console.log("success" + JSON.stringify(content, null, 4));*/ 
     }, 
     function (e) { 
      console.log("it failed! -> " + e); 
     }, 
     { 
      "username": this.username, 
      "password": this.userpass 
     }, 
     {"Accept" : "application/json"} 
    ); 
    } 
} 
app.init(); 
+0

对不起,我的解释确实很差。非常接近我所需要的,唯一的是我希望用户调用一个特定的函数来设置证书,然后记住他们在其他函数的代码中使用它们。 – Bastian

相关问题