I'm just looking at creating an API for our customers to interact with our main Rails 3 application.
For one part, I wanted the json response to contain some a form. Basically some form code that we control and appears on their site.
I have this working ok (simplified):
def login_form
@response = Form.find_by_something(params[:something_else])
if @response
render :status=>200, :json=>{:response => @response}
end
end
And on the client side, I can fetch:
@logins = HTTParty.get("#{set_auth_url}/api/v1/logins.json?auth_token=xyz&something_else=abc").parsed_response
And display the form
= @logins["response"].html_safe
The problem is, the form code has some dynamic variables:
For example:
<div class="login">
<FORM name="form1" METHOD="get" action="<%= request.path %>?">
<INPUT TYPE="HIDDEN" NAME="chal" VALUE="<%= params['challenge'] %>">
<% if @current_location['success_url'] %>
<INPUT TYPE="HIDDEN" NAME="userurl" VALUE="/success">
<% end %>
<input type="hidden" name="UserName" placeholder="Username" value="<%= @user['username']['username'] %>">
<input type="submit" name="login" value="Login" class="btn">
</div>
I'm wondering if this is a good idea? And if so, how can I break those variables out in the html??
If it's not, could someone recommend a nicer way to go about it.
Are those variables known on server-side when preparing the response? In that case, I'd try around with running them through templating engine :json=> { :response => ERB.new(@response).result(binding) }
- client would receive only the html applicable in his case.
Why not use Javascript Template for this as in Jquery Template or Mustache or Handlebar
so keep the form in the on the client side like this
I will describe it using Mustache over here ....
...
<script id="template" type="text/template">
<div class="login">
<FORM name="form1" METHOD="get" action={{request_path}}>
<INPUT TYPE="HIDDEN" NAME="chal" VALUE={{challenges}}>
{{boolean_value}}
<INPUT TYPE="HIDDEN" NAME="userurl" VALUE="/success">
{{/boolean_value}}
<input type="hidden" name="UserName" placeholder="Username" value={{user_name}}>
<input type="submit" name="login" value="Login" class="btn">
</div>
</script>
</html>
Next part is getting the response in form of ajax
The using any Javascript Framework I guess it can be achieved I'm using jQuery over here
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
// make ajax call over here
success: function(data) {
// JSON DATA
var template = $('script#template').html();
$([container where html is place]).html(Mustache.to_html(template,data));
}
})
})
Hope this Help
Not sure how would you want though of plain Form html tag intead of form_tag since it does not contain an authenticity token
Hope this help
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.