[英]How to call Rails form helper with params in jQuery AJAX?(SUPER SIMPLE)
I'm new on Rails, and i think this is super simple, just not used to the syntax. 我是Rails的新手,我认为这非常简单,只是不习惯语法。
this is the jQuery part, 这是jQuery部分,
$.ajax({
type: "get",
contentType: "application/json; charset=utf-8",
url: "/users/search_users",
data: {
name: name
},
dataType: "text",
success: function (result) {
var test = "<%=get_user_list_html(result)%>";
if (result == "User not found") {
alert("User not found");
} else {
//console.log(result);
var peopleData = jQuery.parseJSON(result);
var resultHTML = "<tr>";
resultHTML += "<th></th><th style='display:none'>User ID</th>" + "<th>First Name</th><th>Last Name</th><th>Email Address</th>" + "<th style='display:none'>Time Zone</th>";
resultHTML += "</tr>";
$.each(peopleData, function (index, obj) {
resultHTML += "<tr>";
resultHTML += "<td><input type='checkbox'></td>" + "<td style='display:none;'>" + obj.id + "</td>" + "<td>" + obj.firstname + "</td>" + "<td>" + obj.lastname + "</td>" + "<td>" + obj.email + "</td>" + "<td style='display:none;'>" + "Etc/GMT+9 (Japan)" + "</td>";
//consider now
resultHTML += "</tr>";
});
$("#internal_table").html(resultHTML);
}
},
error: function () {
window.alert("something wrong!");
}
});
in here, i'm going to call get_user_list_html, which is in the helper. 在这里,我将调用助手中的get_user_list_html。
But my problem is, how can i use the result from the respone, i have to send this as a param? 但是我的问题是,我如何使用重发的结果,我必须将其作为参数发送?
if i just put it like that, it says undefined var. 如果我只是这样说,它说未定义的变量。
Ruby code must be executed on the server side, this line: var test = "<%=get_user_list_html(result)%>";
Ruby代码必须在服务器端执行,这一行: var test = "<%=get_user_list_html(result)%>";
won't work after an ajax call, and it should be in a .erb file. 在ajax调用后将无法使用,它应该位于.erb文件中。
You can have a ruby + javascript view template with .js.erb extension but ruby code is always executed before your document loads. 您可以使用扩展名为.js.erb的ruby + javascript视图模板,但是ruby代码始终在文档加载之前执行。
I don't know what the helper does but this is not the way to do it. 我不知道帮手在做什么,但这不是做到这一点的方法。
Solution 1: Render a HTML partial instead of JSON from server. 解决方案1:从服务器呈现HTML部分而不是JSON。 That's make things much easier in you case. 在这种情况下,这使事情变得容易得多。
Solution 2: Use a template to render JSON response, say jQuery template or Underscore template. 解决方案2:使用模板来呈现JSON响应,例如jQuery模板或Underscore模板。
The usage in your case is not good. 您使用的情况不好。 You missed better part in both server and client side. 您在服务器端和客户端都错过了更好的部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.