根据用户输入在javascript中动态创建URL

时间:2018-12-30 08:22:18

标签: javascript conditional url-parameters

我正在尝试根据用户选择动态创建URL

所以我这样写了js:

getPatientProfile(patient, relative, relation, contactNumber, townCity) {

    var p = patient.trim()
    var r = relative.trim()

    var url = 'http://192.168.1.3/api/clinic/patient/profile?patient=' + p + '&relative=' + r ;

    if (relation != null || relation != "" || relation != undefined){
        url += "&relationType=" + relation;
    }
    if (contactNumber != null || contactNumber != ""){
        url += "&contactNumber=" + contactNumber;
    }
    if (townCity != null || townCity != ""){
        url += "&townCity=" + townCity;
    }
    return axios.get(url);
}

但是我仍然得到完整的URL:http://192.168.1.3/api/clinic/patient/profile?patient=vernacular&relative=Dreams&relationType=undefined&contactNumber=&townCity=

如果用户未提供关系,contactNumber和townCity,我想要什么,URL应该只是http://192.168.1.3/api/clinic/patient/profile?patient=vernacular&relative=Dreams

3 个答案:

答案 0 :(得分:1)

当您希望所有条件都为真时,需要使用&&

或者您甚至不需要显式检查所有的falsey值

function getPatientProfile(patient, relative, relation, contactNumber, townCity) {

    var p = patient.trim()
    var r = relative.trim()

    var url = 'http://192.168.1.3/api/clinic/patient/profile?patient=' + p + '&relative=' + r ;

    if (relation){
        url += "&relationType=" + relation;
    }
    if (contactNumber){
        url += "&contactNumber=" + contactNumber;
    }
    if (townCity){
        url += "&townCity=" + townCity;
    }
    return url
}

console.log(getPatientProfile('rel','pat'))

答案 1 :(得分:0)

当用户不提供任何值时,它总是条件为true。   townCity!= null和关系!= null和contactNumber!= null

function getPatientProfile(patient, relative, relation, contactNumber, townCity) 
{

var p = patient.trim()
var r = relative.trim()

var url = 'http://192.168.1.3/api/clinic/patient/profile?patient=' + p + '&relative=' + r ;

if (relation != null && relation != "" && relation != undefined){
    url += "&relationType=" + relation;
}
if (contactNumber != null && contactNumber != ""){
    url += "&contactNumber=" + contactNumber;
}
if (townCity != null && townCity != ""){
    url += "&townCity=" + townCity;
}
return axios.get(url);
}  

答案 2 :(得分:0)

如果您采用json方式,则可以使getPatientProfile(patient, relative, relation, contactNumber, townCity)更通用:

var keys = {
patient : "Thor",
relative : "Loki",
relation : "Brothers",
contactNumber : null,
townCity : ""
};
function getPatientProfile(options){
var url = 'http://192.168.1.3/api/clinic/patient/profile';
  for (key in options){ 
     var separator = url.indexOf('?') !== -1 ? "&" : "?";
     if(!!options[key]){ //checks for the truthy condition of the options[key]
        options[key] = options[key].trim(); //you can also add conditions for the keys which you want to trim.
        url += separator + key + "=" + options[key];
     }
  }
return url;
}

通过这种方式,您可以轻松添加/删除键:)