I have seen some posts regarding this topic and a few blogs, but none seem to mention the output I'm getting.
What I want is to generate a google maps map with information on it. Manually entering the information results in the correct information. So that part works.
Where I'm getting stuck is when I'm going to dynamiccaly create the javascript array with the string with the information I want on my map.
The html code I want to get is:
<script type="text/javascript">
var projects = [
['Kantoor 4.1 bestaande bouw', 52.25446, 6.16024700000003, 'Deventer', '', 'adviseurs', 'rating30'],
['School nieuw 4.0', 52.243161, 4.43677860000003, 'Noordwijk', '', 'adviseurs', 'rating30'],
];
Very simple javascript array, which I thought to create with:
<script type="text/javascript">
var projects = [
#foreach (var item in Model)
{
#HttpUtility.JavaScriptStringEncode("['" + item.Gebouwnaam + "', " + item.LocatieLatitude.ToString().Replace(",", ".") + ", " + item.LocatieLongitude.ToString().Replace(",", ".") + ", '" + item.Plaats + "', '" + item.Gebruiksfunctie + "', '" + item.Licentiehouder + "', '" + item.rating + "'],");
}
];
</script>
However this gives me:
<script type="text/javascript">
var projects = [
[\u0027Kantoor 4.1 bestaande bouw\u0027, 52.25446, 6.16024700000003, \u0027Deventer\u0027, \u0027\u0027, \u0027adviseurs\u0027, \u0027rating30\u0027],
[\u0027School nieuw 4.0\u0027, 52.243161, 4.43677860000003, \u0027Noordwijk\u0027, \u0027\u0027, \u0027adviseurs\u0027, \u0027rating30\u0027],
];
</script>
Escaping the single quotes doesn't work.
What am I doing wrong?
Just tried with
<script type="text/javascript">
var projects = [
#Html.Raw("['" + "aaa" + "', '" + "bbb" + "'],")
];
</script>
it worked and showed ...
<script type="text/javascript">
var projects = [
['aaa', 'bbb'],
];
</script>
You don't want to call JavaScriptStringEncode on the entire string, that will also encode your literal indicators (which are being converted to \u0027 in your example). Instead, call it on each item in your array like this:
<script type="text/javascript">
var projects = [
#foreach (var item in Model)
{
String.Format("['{0}',{1},{2},'{3}','{4}','{5}','{6}']",
HttpUtility.JavaScriptStringEncode(item.Gebouwnaam),
HttpUtility.JavaScriptStringEncode(item.LocatieLatitude.ToString().Replace(",", ".")),
HttpUtility.JavaScriptStringEncode(item.LocatieLongitude.ToString().Replace(",", ".")),
HttpUtility.JavaScriptStringEncode(item.Plaats),
HttpUtility.JavaScriptStringEncode(item.Gebruiksfunctie),
HttpUtility.JavaScriptStringEncode(item.Licentiehouder),
HttpUtility.JavaScriptStringEncode(item.rating)
)
}
];
</script>
I believe you could do most of the heavy lifting in .net and leverage Html.Raw to transform the object for you:
#{
var myObj = Model.Select(i => new {
item.Gebouwnaam,
item.LocatieLatitude.ToString().Replace(",", "."),
item.LocatieLongitude.ToString().Replace(",", "."),
item.Plaats,
item.Gebruiksfunctie,
item.Licentiehouder,
item.rating }).ToArray();
}
<script type="text/javascript">
var jsObj = #Html.Raw(Json.Encode(myObj));
</script>
Since it's touched on in this question, HttpUtility.JavaScriptStringEncode() comes in really handy for strings containing newline characters:
#{ var myNetString = "Hi,\r\nMy name is Joe\r\nAnd I work in a button factory"; }
<script type='text/javascript'>
var myJsString = '#HttpUtility.JavaScriptStringEncode(myNetString)';
</script>
Related
When I insert a string into the JavaScript code I get instead the character ' ---> & # x27;
For example-
string= ['orange','apple','mango'] --> ['orange','apple','mango']
cs code-
foreach (var item in _context.Products)
{
if (!string.IsNullOrEmpty(allProducts))
{
allProducts += ",";
}
allProducts += "'" + item.ProductName + "'";
}
AllProducts = "[" + allProducts + "]";
javascript-
var products =#Model.AllProducts;
According to your description, I suggest you could try to use #Html.Raw method to wraps HTML markup from the string representation of an Object in an HtmlString, without HTML-encoding the string representation.
More details, you could refer to below test demo codes:
#section scripts{
<script>
$(function () {
var products = #Html.Raw(Model.AllProducts);
});
</script>
}
Result:
I'm creating a small web-app for my girlfriend and I that will allow us to keep track of the movies we want to watch together. To simplify the process of adding a movie to the list, I'm trying to use TheMovieDatabase.org's API (supports JSON only) to allow us to search for a movie by title, let the database load a few results, and then we can choose to just add a movie from the database or create our own entry if no results were found.
I'm using jQuery to handle everything and, having never used JSON before, am stuck. I wrote a short bit of code to get the JSON based on my search query, and am now trying to populate a <ul> with the results. Here's what I have.
var TMDbAPI = "https://api.themoviedb.org/3/search/movie";
var moviequery = $("#search").val();
var api_key = "baab01130a70a05989eff64f0e684599";
$ul = $('ul');
$.getJSON( TMDbAPI,
{
query: moviequery,
api_key: api_key
},
function(data){
$.each(data, function(k,v) {
$ul.append("<li>" + k + ": " + v + "</li>");
}
);
});
The JSON file is structured as
{
"page":1,
"results":[
{
"adult":false,
"backdrop_path":"/hNFMawyNDWZKKHU4GYCBz1krsRM.jpg",
"id":550,
"original_title":"Fight Club",
"release_date":"1999-10-14",
"poster_path":"/2lECpi35Hnbpa4y46JX0aY3AWTy.jpg",
"popularity":13.3095569670529,
"title":"Fight Club",
"vote_average":7.7,
"vote_count":2927
}, ...
"total_pages":1,
"total_results":10
}
but all I'm getting is
page: 1
results: [object Object], ...
total_pages: 1
total_results: 10
I've searched quite extensively on the Internet for a solution, but with the little knowledge I have of JSON I wasn't able to learn much from the various examples and answers I found scattered about. What do?
It looks like what you'd like to do is write out some properties of each movie in the list. This means you want to loop over the list in data.results, like this:
// Visit each result from the "results" array
$.each(
data.results,
function (i, movie) {
var $li = $('<li></li>');
$li.text(movie.title);
$ul.append($li);
}
);
This will make a list of movie titles. You can access other properties of movie inside the each function if you want to show more elaborate information.
I added the title to the li using $li.text rather than simply doing $('<li>' + movie.title + '</li>') since this will avoid problems if any of the movie titles happen to contain < symbols, which could then get understood as HTML tags and create some funny rendering. Although it's unlikely that a movie title would contain that symbol, this simple extra step makes your code more robust and so it's a good habit to keep.
You need to traverse the results object. In the $.each function change data for data.results
You can use a simple for loop to iterate over the list/array. in the example below i am appending a list item containing the value of the key results[i].title. you can append the values of as many valid keys as you would like to the div.
var TMDbAPI = "https://api.themoviedb.org/3/search/movie";
var moviequery = $("#search").val();
var api_key = "baab01130a70a05989eff64f0e684599";
$ul = $('ul');
$.getJSON( TMDbAPI,
{query: moviequery,api_key: api_key},function(data){
var results = data.results;//cast the data.results object to a variable
//iterate over results printing the title and any other values you would like.
for(var i = 0; i < results.length; i++){
$ul.append("<li>"+ results[i].title +"</li>");
}
});
html
<input id="search" type="text" placeholder="query" />
<input id="submit" type="submit" value="search" />
js
$(function () {
$("#submit").on("click", function (e) {
var TMDbAPI = "https://api.themoviedb.org/3/search/movie";
var moviequery = $("#search").val();
var api_key = "baab01130a70a05989eff64f0e684599";
$.getJSON(TMDbAPI, {
query: moviequery,
api_key: api_key
},
function (data) {
$("ul").remove();
var ul = $("<ul>");
$(ul).append("<li><i>total pages: <i>"
+ data.total_pages + "\n"
+ "<i>current page: </i>"
+ data.page
+ "</li>");
$.each(data.results, function (k, v) {
$(ul).append("<li><i>title: </i>"
+ v.original_title + "\n"
+ "<i>release date: </i>" + v.release_date + "\n"
+ "<i>id: </i>" + v.id + "\n"
+ "<i>poster: </i>"
+ v.poster_path
+ "</li>");
});
$("body").append($(ul))
});
});
});
jsfiddle http://jsfiddle.net/guest271314/sLSHP/
I'd like to build a string based on values defined in an html form only if they have been populated. I've successfully parsed the form fields and dropdown with a for loop ($.each()) but my ultimate goal is to dynamically build a string with the results. The string is being used to create a REST query, this is currently the only way to search based on our technologies. Does anyone have a recommended solution?
thx in advance
sample html element:
<input data-param=" prefix like '%" data-name="prefix" class="prefix uno" type="text" placeholder="pre">
working btn click event loop to capture filled in form fields:
var children = $(this).parent().children('.uno');
$.each(children, function(i, val){
if($(val).val() !== ''){
console.log($(val).data('name') + " "+ $(val).data('param') + " " + $(val).val());
}
});
goal:
var newString = field1.param + field1.val + '% ' + field2.param + field2.val + '% ';
translated:
var newString = prefix like '%01%' and name like '%tree%';
Thanks David Fregoli for the jquery serialize reference, that was close, but the solution ended up being to place the strings into a single array, change it toString(), and remove the ',' from the new string.
code:
var samp = [],
thisVal = $(this).parent().children('.uno');
$.each(thisVal, function(i, val){
if($(val).val() !== ''){
samp.push(
$(val).data('param'),
$(val).val(),
$(val).data('close')
);
}
});
itQuery.where = samp.toString().replace( /,/g , '');
result search string:
"number like '%08%' and field = 34"
I don't know JavaScript but I need to use SPServices on my company intranet. I need to write the fieldNames into some divs on my page, how do I do this? Here's the SPServices script:
<script type="text/javascript">
$( document ).ready(function(){
var thisUsersValues = $().SPServices.SPGetCurrentUser({
fieldNames: ["FirstName", "LastName", "Picture", "JobTitle", "WorkPhone", "WebSite",],
debug: false
});
</sript>
Thanks!
var thisUsersValues = $().SPServices.SPGetCurrentUser({
fieldNames: ["FirstName", "LastName"],
debug: false
});
var name = thisUsersValues.FirstName + " " + thisUsersValues.LastName;
alert('Your name: ' + name);
I tested this and this is the correct usage. Just use "." syntax, or you could use thisUserValues['FirstName']; and thisUserValues['LastName']; to retrieve the properties.
From there, the other answer posted by Cana was correct:
var userDescription = "<div>" + name + "</div>";
var obj = $("#someObjId").append(userDescription);
I know this is old (I'm new to the site) but here is another option based off your JavaScript using DOM. It pulls the currentuser into a variable and using a DOM inserts into a div. This also works with an input field. Notice the .src for the picture.
<script type="text/javascript" language="javascript">
$(document).ready(function() {
var userdetails = $().SPServices.SPGetCurrentUser(
{
fieldNames: ["ID","EMail","UserName","FirstName","LastName","Picture","JobTitle","WorkPhone","Office"],
debug:false
});
document.getElementById('NameExample').innerHTML = (userdetails.FirstName + " " + userdetails.LastName);
document.getElementById('PhotoExample').src = (userdetails.Picture);
document.getElementById('EmailExample').innerHTML = (userdetails.EMail);
document.getElementById('TitleExample').innerHTML = (userdetails.JobTitle);
document.getElementById('OfficePhoneExample').innerHTML = ("Office" + " " + userdetails.WorkPhone);
document.getElementById('nameInputField').value = (userdetails.FirstName + " " + userdetails.LastName);
document.getElementById('emailInputField').value = (userdetails.EMail);
document.getElementById('OfficePhoneField').value = (userdetails.WorkPhone);
document.getElementById('titleInputField').value = (userdetails.JobTitle);
});
</script>
<div>
<span id="OfficePhoneExample"></span></br>
<span id="EmailExample"></span></br>
</div>
Maybe this could help you :
var $userDescription = "<div>"+ thisUsersValues.toString() +"</div>";
$("#yourDivID").append($userDescription);
I want to pull from a tumblr blog and display it on another webpage using javascript.
I'm using the $TUMBLR_BLOG/api/read/json feed which provides a variable filled with the information from the blog post.
I want to print everything up to the "<!-- more -->" set of characters in the 'regular-body' section, ie. I don't want to print everything in the 'regular-body' just up to that more section.
Any thoughts on how to do that?
Eg. API read: http://blog.intercut.yegfilm.ca/api/read/json
Eg. Basic code I'm using:
<script type="text/javascript" src="http://blog.intercut.yegfilm.ca/api/read/json"></script>
<script type="text/javascript">
// The variable "tumblr_api_read" is now set.
document.write(
'<h3> ' + tumblr_api_read.posts[0]['regular-title'] + '</h3>' +
tumblr_api_read.posts[0]['regular-body']);
</script>
<script type="text/javascript">
// The variable "tumblr_api_read" is now set.
var url = tumblr_api_read.posts[0]['url'];
var title = tumblr_api_read.posts[0]['regular-title'];
var body = tumblr_api_read.posts[0]['regular-body'];
body = body.substring(0,body.indexOf("<!-- more -->"));
document.write('<h3> ' + title + '</h3>' + body);
</script>
Simple as that :)
Something like responseData.split("<!-- more -->")[0] ?
Get the index of the <!-- more --> and print the substring upto that index.
sampleString = "Foo <!-- more --> Bar";
moreIndex = sampleString.indexOf("<!-- more -->");
if (moreIndex > 0) {
console.log(sampleString.substring(0, moreIndex));
}
JSFiddle
Use the javascript SubString() method:
Example:
var mystring = 'Hello World <!-- more -->';
alert(mystring.substring(0,mystring.indexOf("<!-- more -->")));
jsFiddle: http://jsfiddle.net/8CXd8/
Documentation: http://www.w3schools.com/jsref/jsref_substring.asp