Calling a Rails function from a Javascript function
I am converting some php code into a Ruby script and I am attempting to call the url of a Rails function from Javascript completely that unrelated to the Rails app itself. To explain further say I have a rails function bar() in a controller foo that is accessible from the server's url.
http://localhost:3000/foo/bar?param1=asdf¶m2=word1;word2
When this was foo.php I simply did this:
xmlhttp = new XMLHttpRequest();
xmlhttp.open("post", "my.domain/foo.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-ur开发者_JAVA百科lencoded");
xmlhttp.send("param1=asdf¶m2=word1;word2");
But to get it to work with my Rails code I'm having to do this:
xmlhttp = new XMLHttpRequest();
xmlhttp.open("post", "my.domain/foo/bar?param1=asdf¶m2=word1;word2", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
Which is fine, it's adding values to the DB like I want it to but the entry for param2 is only getting word1. It reaches the semicolon and ignores word2. I imagine this is just because this is how URL's handles semicolons, etc. I figure I could get it to behave like it once did by putting my post params into the send function of XMLHttpRequest() but that isn't working. Is there another/better way of making such a call in the case of RoR?
You have to encode the parameter values (and the names, if you're not certain they'll be clean):
xmlhttp.open("post", "my.domain/foo/bar?param1=" + encodeURIComponent("asdf") + "¶m2=" + encodeURIComponent("word1;word2"), true);
Obviously if the parameter values are variables (like from "value" attributes of input fields) then you'd plug that in instead of the "word1;word2" constants in the above :-)
The semicolon will come out as "%3B" after encoding.
Oh, and this isn't a PHP vs. Rails thing - it's just a basic thing with "GET" parameters in URLs.
精彩评论