in destroy.js.erb it works
$("<%= escape_javascript(render #comment) %>").appendTo("#commentlist");
how to do it for slim?
I have tried
$("= escape_javascript(render #comment)").appendTo("#commentlist");
and renamed to destroy.js.slim, but its not works
By default, Slim tries to convert your code into HTML markup, so your current code produces an error. You can check it by viewing http://<website_adress>/something/destroy.js
To fix this, you have to use pipe symbol, here is excerpt from official documentation:
The pipe tells Slim to just copy the line. It essentially escapes any processing. Each following line that is indented greater than the pipe is copied over.
http://rdoc.info/gems/slim/frames
Also, ruby embedding work a bit different for Slim, you have to use #{ruby code} instead of equal sign, if you embedding it into string.
To sum things up this is how it should look like to work:
|
$("#{escape_javascript(render #comment)}").appendTo("#commentlist");
This way you can add more lines without prepending code with pipe each time.
Just to note, there is also shortcut for escape_javascript called simply j, so you could've used this code:
|
$("#{j(render #comment)}").appendTo("#commentlist");
in view
- url_ajax = 'http://gilcierweb.com.br'
- content_for :js do
javascript:
var ids = new Array();
$('input[type=checkbox]:checked').each(function () {
var id = $(this).val();
ids.push($(this).val());
$('.' + id).fadeOut("slow").hide(1600).remove();
});
$.ajax({
type: "POST",
url: "#{escape_javascript(url_ajax)}",
data: {id_img: ids},
success: function (data) {
$('.contestants_list').append(data);
}
});
in layout
-if content_for?(:js)
== yield(:js)
Related
I am currently trying to parse and xml file that is of the following format:
<holidays>
<holiday1> text </holiday1>
<holiday2> text </holiday2>
<holiday3> text </holiday3>
<holiday4> text </holiday4>
...
with the following code:
$.ajax({
url: '<filename>',
dataType: 'xml',
success: xmlParser
});
function xmlParser(xml) {
$('#load').fadeOut();
$(xml).contents().each(function () {
$("#holidates").append('<p>' + $(this).text() + '</p>');
});
$(".dates").fadeIn(2000);
}
The current output is:
<p>01/13/2016 02/02/2016 12/24/2015 12/24/2015 12/24/2015 12/29/2015 12/30/2015 11/23/2015 01/01/2016 01/26/2016 12/25/2015</p>
I would prefer:
<p>01/13/2016</p>
<p>02/02/2016</p>
<p>12/24/2015</p>
....
Is there a way to achieve his without formatting the xml file? The file is part of another system and is required in the indicated format.
Many thanks.
Given your feedback, the problem is clear. You take the text value of the root element. This however just concatenates all text elements from its children.
I am not a pro when it comes to ajax, but the idea is to select the 'holiday' tags and run an 'each' on that set.
Your XML structure makes it a bit harder than it should be because of the integers in the name. If you are certain that all the children of the 'holidays' tag are 'holidayx' tags then you could just take all children.
$(xml).contents().find('holidays').children().each(function () {
$("#holidates").append('<p>' + $(this).text() + '</p>');
});
I would suggest trying something like that.
I found this page How can I pretty-print JSON using node.js? and I think it's useful, but I have one question: I have a page that give a result from a request sparql in an array, and I want to take just one line of this results with a button "add" that is insert in the last column of the line, and when I take the line in Json I want to write it in a file json that already exist with other data. The button call the next function:
function add(param) {
res= param;
$.ajax({
type: "POST",
url: "....",
data: { nom:resource,abstract:resume,photo:src,indice: res ,fichier:$("#myselect" ).val()}
})
.done(function( msg ) {
alert( "ajout réussie"+msg);
window.location.reload();
});
};
Where res is the index for the line that I want to add, and data all data I need to add.
So I want to know how I can change this code to use the last code posted by "Larry Battle". I have to put his code in a file "add.js" and I call this file in url? Or How?
Link for my example: https://www.dropbox.com/s/noyh1ltwljlpevw/Capture%20du%202014-05-01%2019%3A05%3A04.png
The easiest way might be to require the original json file, add the new data in memory, then save the object back as a pretty json file (overwriting the original if you like).
I'm not sure what you meant by "res is the index of the line I want to add", so I'll assume it's going to be the property name in the javascript object that you serialize to JSON. So in general it'd look something like this:
var fileData = require('/path/to/jsonData.json');
// fileData is now a JS object that was parsed from the json file); this is a sync operation.
fileData[res] = data; // data object from your existing code.
// write fileData to a JSON file like you were going to do before.
I'm using Nokogiri, at this moment, I have variable which contains code of some page: doc = Nokogiri::HTML(open(page)). There is script in code, ajax calls:
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$("#menu").kendoMenu();
$('.menu_item').on('click', function (e){
$.ajax({
url: '/movie/101299-the-hunger-games-catching-fire/images?kind=backdrop&language=' + $(this).attr('alt') + '&translate=false',
cache: false
}).done(function(response) {
$('#image_panel').html(response);
});
});
$.ajax({
url: '/movie/101299-the-hunger-games-catching-fire/images?kind=backdrop&language=&translate=false', //goal
cache: false
}).done(function(response) {
$('#image_panel').html(response);
});
});
</script>
There is some way to get second request url, and place it to the variable, I need to go to this url. Unfortunately I didn't find something about it, maybe phantomjs can help me?
I think you will to manually parse the script element. You can do this by using Nokogiri to get the text of the script element. Then use a regexp to find the last url:
Assuming the script is the first on the page, you can do:
url = doc.at_css('script').text.scan(/url: '(.*)'/).last.first
The following breaks the script down to provide explanation of each step:
# Get the text of the script element
# Note that this assumes it is the first script element (you may need to be more specific)
script = doc.at_css('script').text
# Find all urls in the script
urls = script.scan(/url: '(.*)'/)
# Of the urls found, take the last one
url = urls.last
# url is actually an array of length 1, since we used a matching group in the regex
# Take the first element of the array to get the url as a string
url = url.first
#=> "/movie/101299-the-hunger-games-catching-fire/images?kind=backdrop&language=&translate=false"
Trying to use Backbone's navigate property.
this.navigate("week/" + companyName + "/" + employeeNo + "/" + weekEnd, { trigger: true, replace: false });
The code above is executed once.
It hits this:
routes: {
"week/:companyName/:employeeNo/:weekEnd": "getWeek"
},
And then this function gets hit twice:
getWeek: function (companyName, employeeNo, weekEnd) {
console.log('getWeek:', companyName, employeeNo, weekEnd);
}
It is logged twice in Firefox, only once in IE and Chrome.
What's the issue here? I originally didn't even have trigger set to true, and Firefox ignored that and still triggered the URL.
I had a similar issue recently with Firefox doing two server calls after a Backbone.navigate. In my case it was because we had not encoded the string. Does your company name have any characters which should be encoded?
You could try:
this.navigate("week/" + escape(companyName) + "/" + employeeNo + "/" + weekEnd, { trigger: true, replace: false });
Stepping in as I've run into the same issue and got to the underlying problem here.
As everyone mentioned before, the problem comes from URL encoding. Now as to why the issue only appears in Firefox...
Let's start by summarizing quickly how the routes are called when the hash changes. There are 3 key functions here:
loadUrl: this function is the one that will call your route handler.
navigate: this is the function used to change the route manually. If the trigger flag is set to true, the function will call loadUrl.
checkUrl: this function is set as callback for the onhashchange event on the window object (when it's available of course). It also runs loadUrl on certain conditions.
Now, we're getting to the interesting part.
When you run navigate, Backbone will cache the fragment you navigated to. The hash changing, checkUrl will also be called. This function will then check if the cached hash equals the current one, so as not to execute loadUrl if you called navigate before, because it would mean it has already been called. To make that comparison, checkUrl gets the current hash with the function getFragment, which uses getHash. Here is getHash's code:
getHash: function(window) {
var match = (window || this).location.href.match(/#(.*)$/);
return match ? match[1] : '';
},
And you got your problem. location.href is URI-encoded in firefox, but is not in chrome. So if you navigated to another hash (with or without the trigger flag), in firefox, Backbone will cache the unencoded version of your hash, and then compare it with the encoded version. If your hash contained a should-be-encoded character, the result of the comparison will be negative, and Backbone will execute the route handler it should not execute.
As per the solution, well, folks said it before, your URIs should be encoded.
Question may be old, but for me this was still relevant. Encoding the url wasn't enough in my case. I replaced the GetHash() function in Backbone with:
getHash: function (t) {
var e = (t || this).location.href.match(/#(.*)$/);
return match ? this.decodeFragment(match[1]) : '';
}
This HAML
%script{:type => "text/javascript"}
:plain
$(document).ready(function() {
bar();
var foo = foo_func("#{}");
});
as expected gives this:
<script type='text/javascript'>
$(document).ready(function() {
bar();
var foo = foo_func("");
});
</script>
But this ALMOST IDENTICAL HAML (changed only bar()to prep()):
%script{:type => "text/javascript"}
:plain
$(document).ready(function() {
prep();
var foo = foo_func("#{}");
});
gives this:
<script type='text/javascript'>
$(document).ready(function() {
prep();
var foo = foo_func("");
});
</script>
NOTE THE MESSED UP INDENTATION in the second case.
Why would changing bar()to prep() cause this weird difference?
This is being caused by the characters pre in prep() matching a regex that Haml is using to deal with whitespace.
In Haml you use whitespace to specify the contents of elements, and normally this is okay since when viewing HTML whitespace is “squashed” so that it appears as a single character. However, whitespace is important in some HTML elements (pre, code and textarea), and Haml tries to detect and deal with these elements. In this case the regex is matched and the block after the first line isn’t indented.
This code has been changed in the latest version (currently 4.0.1.rc.1) and this doesn’t happen in that version. I’ve also created a pull request that fixes the regex in the 3-1 branch.