weixin_33716557 2017-05-10 17:35 采纳率: 0%
浏览 17

通过Ruby将HTML表单转换为MongoDB

I am trying to learn a new skill, just as a hobby, and while I've learned a lot, there are still things that I get confused on - and this is one of them.

I have a MongoDB set up with a DB = phone and a collection = records which stores, as you may have guessed, phone directories. I created a JSON file and imported everything and all went well.

Then I created a Ruby / Sinatra app to display the data in a table. That all works great as well.

Now I want to use an HTML form to submit a new user to the database. My basic form for testing is as follows and is located in the Sinatra public directory as myTest.html

<form id="form">
    First name:<br>
    <input type="text" name="fname" value="Mickey">
    <br> Last name:<br>
    <input type="text" name="lname" value="Mouse">
    <br><br>
    <input type="submit" value="Submit" id="commit">
  </form>
  <script>

(I have left out the action=" ", since I was trying to do this via AJAX, but it didn't work) This was my AJAX attempt:

<script>
    $(function() {
      $.ajax({
        url: 'http://localhost:4567/api/v1/myTest',
        type: 'post',
        dataType: 'json',
        jsonp: 'json', // mongod is expecting the parameter name to be called "jsonp"
        success: function(data) {
          //console.log('success', data);
          console.log("Success");
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          console.log('error', errorThrown);

        }
      });
    });

In my Ruby file, phone.rb, I have this:

get '/myTest' do
result = Record.collection.insert_one({ :fname =>"Justin"})
end

I have verified that this will work.

Where I am stuck is connecting the two (or do I even need to ?) When I click the submit button on the form, I get a URL encoded string like this:

localhost:4567/myTest.html?fname=Justin&lname=Smith

How do I take the URL data from teh form, and insert it into Mongo as a new document?

I have spent two days looking for an answer, but almost all the information on the web comes back as Rails, which I'm not using. I want to learn to do everything in Ruby first. When I look at the problem from teh Javascript side, virtually all references point to Node.js, which I am not using.

Any help would be appreciated, or at least a nod in the right direction. Thanks

UPDATE I obviously make a mistake in my Ruby - it should be POST. So I made a new Ruby block, and when I access it directly from the browser and enter localhost/api/v1/myTest?fname=Mickey&lname=Mouse, it enters the info into the database

post '/myTest' do
fname = params[:fname]
  lname = params[:lname]
  Record.collection.insert_one({'fname' => fname, 'lname' => lname})
end

On the form, I've tried to add the following:

<form id="form" method="POST" action="/myTest">
    First name:<br>
    <input type="text" name="fname">
    <br> Last name:<br>
    <input type="text" name="lname">
    <br><br>
    <input type="submit" value="Submit" id="commit">
  </form>
<script>
    $(function() {
      //hang on event of form with id=myform
      $("#form").submit(function(e) {

        //prevent Default functionality
        e.preventDefault();

        //get the action-url of the form
        var actionurl = '/myTest';


        $.ajax({
          url: actionurl,
          type: 'post',
          dataType: 'application/json',
          data: $("#form").serialize(),
          success: function(data) {
            console.log('success')
          }
        });

      });

    });
  </script>

I am not able to hit the Ruby /myTest. I keep getting a "Sinatra Doesn't Know this Ditty" 404. COuld it be that I am not using Sinatra to create the HTML in the Views folder as erb? My pages are in the Public folder and are written independently of Sinatra.

  • 写回答

2条回答 默认 最新

  • weixin_33749242 2017-05-10 19:21
    关注

    First of all, in jour javascript code you're not sending any form data, i.e. first & last name (see jQuery $ajax docs). Second of all, you're trying to send a POST request, while your Sinatra app defines a GET endpoint. Once you make sure your Sinatra app receives correct data sent from the HTML form you can easily create new record in MongoDB using mongo-ruby-driver

    评论

报告相同问题?