在js.erb上渲染json的轨道上的红宝石

时间:2016-03-07 19:30:59

标签: javascript ruby-on-rails ruby json

在控制器的create方法中,我有以下代码:

<?php
$servername = "localhost";
$username = "USER";
$password = "PASS";
$dbname = "DATABASE";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$first_spouse = $_POST['first_spouse'];
$last_spouse = $_POST['last_spouse'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$phonehome = $_POST['phonehome'];
$phonecell = $_POST['phonecell'];
$email = $_POST['email'];
$dob = $_POST['dob'];
$occupation = $_POST['occupation'];
$shirt_size = $_POST['shirt_size'];
$cap_size = $_POST['cap_size'];
$shirtnum1 = $_POST['shirtnum1'];
$shirtnum2 = $_POST['shirtnum2'];
$desc = $_POST['desc'];
$bylaws_rules = $_POST['bylaws_rules'];
$umpires = $_POST['umpires'];
$alcohol = $_POST['alcohol'];
$waiver = $_POST['waiver'];


$sql="INSERT INTO 'softball_reg_2016' (first_name, last_name, first_spouse, last_spouse,
 address, city, state, zip, phonehome, phonecell, email, dob, occupation, shirt_size,
  cap_size, shirtnum1, shirtnum2, desc, bylaws_rules, umpires, alcohol, waiver)
  VALUES ('$_POST[first_name]', '$_POST[last_name]', '$_POST[first_spouse]', '$_POST[last_spouse]',
 '$_POST[address]', '$_POST[city]', '$_POST[city]', '$_POST[state]', '$_POST[zip]',
 '$_POST[phonehome]', '$_POST[phonecell]', '$_POST[email]', '$_POST[dob]', '$_POST[occupation]',
 '$_POST[shirt_size]', '$_POST[cap_size]', '$_POST[shirtnum1]', '$_POST[shirtnum2]',
 '$_POST[desc]', '$_POST[bylaws_rules]', '$_POST[umpires]', '$_POST[alcohol]', '$_POST[waiver]')";

echo "Connected successfully";

mysqli_close($conn);
?> 

完美无缺。现在我想在create.js.erb中移动它,以便有可能执行添加js。但是我不知道如何在create.js.erb中渲染上面的json。

知道如何做到这一点。提前谢谢!

1 个答案:

答案 0 :(得分:0)

如果我理解正确,那么您要实现的是能够在js.erb视图中访问您的JSON。为了实现这一点,我过去所做的是以下内容:

在你的create.js.erb中:

var yourJSON = JSON.parse("<%= raw(j render :partial => '/users/photos/card', object: @photo, as: 'photo') %>");

在你的控制器中:

respond_to do |format|
  format.js # This will render the create.js.erb
  format.json { render :partial => '/users/photos/card' } # Leave this one in case you also want to be able to respond to this format i.e: "http://localhost:3000/users/photos/card/id.json"
end

希望这有帮助!

P.S:如果你想要达到不同的目的,请告诉我。