I'm using Javascript Object literals , but i can't concatenate string attributes.
var cart = {
baseURL : "http://www.domain.com/",
addURL : this.baseURL + "cart/add",
deleteURL : this.baseURL + "cart/delete",
totalURL : this.baseURL + "cart/total",
// functions
}// cart
i get a link as http://www.domain.com/undefinedcart/add
Please any help,
Thanks in advance
You don't have access to the baseURL in that way. Thats because this is actually window and it probably does not has property baseURL.
You can use Immediately-Invoked Function Expression (IIFE) and closure instead:
var cart = function () {
var baseURL = "http://www.domain.com/";
return {
addURL : baseURL + "cart/add",
deleteURL : baseURL + "cart/delete",
totalURL : baseURL + "cart/total"
};
}();
The problem isn't concatenation within the context of the object, it's that the this you're looking for doesn't exist yet. A simple solution might look like this:
var baseURL = "http://www.domain.com/";
var cart = {
baseURL : baseURL,
addURL : baseURL + "cart/add",
deleteURL : baseURL + "cart/delete",
totalURL : baseURL + "cart/total",
}
Or this:
var cart = new function() {
this.baseURL = "http://www.domain.com/";
this.addURL = this.baseURL + "cart/add";
this.deleteURL = this.baseURL + "cart/delete";
this.totalURL = this.baseURL + "cart/total";
};
The variable "this" is a instance of Window, so you can't use "this" as "cart"
Related
I am learning Javascript. I wrote a JS to return a Json-type value.
var generateUrl = function(Name, Letter, rootUrl, V1) {
rootUrl = rootUrl || Letter;
return {
classname: 'mycss-' + Letter,
text: Name,
url: rootHref.replace(Rex, "$1" + rootUrl + "."),
onclick: {
fn: clickFn,
obj: V1
}
};
};
I want to add a if statement inside url:.
For example, if Name = google, url won't use this logic rootHref.replace(Rex, "$1" + rootUrl + "."), instead it will directly return an url.
I have searched for an answer quite a while but still have no luck. May someone tell me how to add a if statement logic in my code.
Try as follows
url: (num == 1) ? Link1 : Link2,
On my site i am using jQuery's ajax this way:
$.ajax({
type: 'GET',
url: productSearch.searchUrl,
data: parameter,
dataType: 'json'
}
"data" contains all parameters.
On some state i want to redirect the user to the same page but with all paramters from "data" appended.
Example
data = {
"par1" = "value1",
"par2" = "value 2"
}
current url: www.google.com
should be redirected to www.google.com?par1=value1&par2=value2.
How to do this (with jQuery?)?
with simple javascript
window.location.href = "www.google.com?" + Object.keys(data).map(function(key){
return key + "=" + data[key];
}).join("&");
And yes, data key can be encoded as well
window.location.href = "www.google.com?" + Object.keys(data).map(function(key){
return encodeURIComponent(key) + "=" + encodeURIComponent(data[key]);
}).join("&");
Since you're using jQuery, $.param() will serialize an object like that. Then you just append the resulting string to the URL.
try:
var data = {
"par1": "value1",
"par2": "value 2"
}
var params = $.param(data);
if (location.href.match(/\?/)) {
location.href += params;
} else {
location.href += '?' + params;
}
You can try this:
params = $.params(data);
window.location.href = window.location.href +'?'+params;
I'd like to add a parameter after an URL in a Javascript function.
The full URL I'd like to have is: https://my-url.com/section1/section2/here_a_random_number.json?lang=en
This is the ".json?lang=en" that I'd like to add at the end of the URL.
Here my function (in a Google script, linked to a sheet):
function myfunction(randomnumber) {
var myUrl = "https://my-url.com/section1/section2/" + escape(randomnumber);
var jsonData = UrlFetchApp.fetch(myUrl);
var jsonString = jsonData.getContentText();
var jsonObject = JSON.parse(jsonString).result;
var name = (jsonObject.name);
Utilities.sleep(2000);
return name;
}
Where could I put/add my language parameter ?
Just add it to the end of the URL:
var myUrl = "https://my-url.com/section1/section2/" + escape(randomnumber) + ".json?lang=en";
try to replace
var myUrl = "https://my-url.com/section1/section2/" + escape(randomnumber);
by
var myUrl = "https://my-url.com/section1/section2/" + escape(randomnumber)+".json?lang=en";
I am generating an URL in JavaSctipt.
The first time I generate this URL I get the correct URL:
E.g. **http://localhost:54415/NffCall/Details/DK/6607726**
But the next time I generate the link I get the previous link combined with current parameters:
E.g. http://localhost:54415/NffCall/Details/DK/6607726/DK/6608146
The code which genrates my URLs looks like this:
var actionUrlBase = '#Url.Action("Details", "NffCall")';
var actionUrl = actionUrlBase + '/' + countryCode + '/' + orderNumber;
window.location.href = actionUrl;
What shall I do to generate the correct link every time?
EDIT:
I will just paste how the RouteCollection looks like:
routes.MapRoute(
name: "CountryCodeOrderNumberDetails",
url: "{controller}/{action}/{countryCode}/{orderNumber}",
defaults: new { controller = "NffCall", action = "Details", countryCode = (string)null, orderNumber = (int?)null },
constraints: new { countryCode = "[a-zA-Z]{2}", orderNumber = "[0-9]+" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Use the Helper #Url.RouteUrl instead.
var actionUrlBase = '#Url.RouteUrl("Default",new {action="Details", controller= "NffCall"},Request.Url.Scheme)';
var actionUrl = actionUrlBase + '/' + countryCode + '/' + orderNumber;
window.location.href = actionUrl;
This site explains it very well: http://www.patridgedev.com/2011/08/22/subtleties-with-using-url-routeurl-to-get-fully-qualified-urls/
In java script I get this error
Uncaught ReferenceError: baseUrl is not defined
window.Configurations = Configurations = {
baseUrl: 'https://mysite.com/',
detailsEventCustom: baseUrl + 'DetailsEventCustom?EventId=',
addEventCustom: baseUrl + 'AddEventCustom',
listAllEventsCustomForDate: baseUrl + 'ListAllEventsCustomForDate?DateToLookUp=',
dashboardEventsCustom: baseUrl + 'DashboardEventsCustom',
listAllTimetableEventsCustom: baseUrl + 'ListAllTimetableEventsCustom',
updateEventCustom: baseUrl + 'UpdateEventCustom?EventId=',
deleteEventCustom: baseUrl + 'DeleteEventCustom?EventId='
};
Could you point me out what I am doing wrong here?
you cannot do it like this
when you are accessing the object hasn't been made try doing this instead
var baseUrl = 'https://mysite.com/';
window.Configurations = Configurations = {
baseUrl: baseUrl,
detailsEventCustom: baseUrl + 'DetailsEventCustom?EventId=',
addEventCustom: baseUrl + 'AddEventCustom',
listAllEventsCustomForDate: baseUrl + 'ListAllEventsCustomForDate?DateToLookUp=',
dashboardEventsCustom: baseUrl + 'DashboardEventsCustom',
listAllTimetableEventsCustom: baseUrl + 'ListAllTimetableEventsCustom',
updateEventCustom: baseUrl + 'UpdateEventCustom?EventId=',
deleteEventCustom: baseUrl + 'DeleteEventCustom?EventId='
};
This is a scoping problem. You are still building the object between the curly braces, and all values are calculated before they are assigned to the object. baseUrl simply doesn't exist yet when you are using it to assign the other values. You should do something like this instead:
var baseUrl = 'https://mysite.com/'
window.Configurations = Configurations = {
baseUrl: baseUrl,
detailsEventCustom: baseUrl + 'DetailsEventCustom?EventId=',
addEventCustom: baseUrl + 'AddEventCustom',
listAllEventsCustomForDate: baseUrl + 'ListAllEventsCustomForDate?DateToLookUp=',
dashboardEventsCustom: baseUrl + 'DashboardEventsCustom',
listAllTimetableEventsCustom: baseUrl + 'ListAllTimetableEventsCustom',
updateEventCustom: baseUrl + 'UpdateEventCustom?EventId=',
deleteEventCustom: baseUrl + 'DeleteEventCustom?EventId='
};