将数据从Javascript实时传递到HTML?

时间:2014-04-23 14:03:39

标签: javascript jquery html ruby-on-rails ajax

我累了,迷路了。似乎以脱节的MVC /多语言方式编码的巨大部分挑战是找出在适当的时间在不同部分之间传递值的方法。

以下代码不起作用。

我有一个JS文件:

// GET DATA FROM A MAP PIN THAT A USER CLICKS ON
// The data is read from our API for that pin.

function getPinData(id, template) {
  $.ajax({
    url: "/api/pins/"+id,
    type: "GET",
    data: "JSON"
  }).success(function(data){

    var pinTitle = data["pin"]["activity"];
    var pinDescription = data["pin"]["description"];
    var pinGuideFirstName = data["pin"]["guide_first_name"];
    var pinGuideLastName = data["pin"]["guide_last_name"];
    var pinGuideRating = data["pin"]["guide_rating"];
    var pinGuideEmail = data["pin"]["guide_email"];

    var guideData = [pinGuideFirstName, pinGuideLastName,
                     pinTitle, pinGuideEmail];

    // the contents of guideData now need to be passed to a different page.

    // jQuery selector - messageGuideButton is simply a button that will bring up a
    // pop-up form that allows the user to send a message to the guide. I want to send          
    // guideData to this html form

    $( "#messageGuideButton" ).on("click", function() {
      $.ajax({
        url: "/message.html",
        type: "GET",
        data: guideData,
        success: function(response) {

          // Checking to see if guideData still exists in this function - it exists

          console.log("Guide Data in AJAX: " + guideData);   

          $('.popin').html(response).fadeIn();
          },
        beforeSend: function() {
          $('.popin').addClass('loading');
          },
        complete: function() {
          $('.popin').removeClass('loading');
          }
        });
      });
    })
}

message.html,这是一个弹出框,而不是单独的页面。

<div class="ui raised segment signin">
  <div class="cmborder">

    <script>
      console.log("Guide Data in Form: " + guideData); 
      // guideData comes back as undefined
      // I guess arrays can't be passed via GET
    </script>

    // This is Rails code and Rails' form helper methods

    <%= form_tag("/message", method: "post") do %>
      <!-- <p>Go ahead and message your guide</p> -->
      <div class="two fields">
        <div class="inline field">

    // I want to add the guideData into a hidden form field for submission later

         <%= hidden_field_tag 'message[guideFirstName]', guideData[0] %>
        </div>
        <div class="inline field">
          <%= hidden_field_tag 'message[guideLastName]', guideData[1] %>
        </div>
        <div class="inline field">
          <%= hidden_field_tag 'message[pinTitle]', guideData[2] %>
        </div>
        <div class="inline field">
          <%= hidden_field_tag 'message[guideEmail]', guideData[3] %>
        </div>

        <div class="field">
          <label>First Name</label>
          <%= text_field_tag 'message[firstName]', @current_user.first_name, class: "ui input", placeholder: "First Name" %>
        </div>
        <div class="field">
          <label>Last Name</label>
          <%= text_field_tag 'message[lastName]', @current_user.last_name, class: "ui input", placeholder: "Last Name" %>
        </div>
      </div>
      <div class="field">
        <label>Message title</label>
        <%= text_field_tag 'message[messageTitle]', nil, class: "ui input", placeholder: "Message Title" %>
      </div>
      <div class="field">
        <label>Message</label>
        <%= text_area_tag 'message[messageBody]', nil, class: "ui input", placeholder: "Message Body" %>
      </div>
      <div class="inline field">
        <%= hidden_field_tag 'message[currentUserEmail]', @current_user.email %>
      </div>
      <%= submit_tag "Submit", class: "ui blue submit button" %>

    <% end %>
  <span class='close_message' id="messageclose">&times;</span>
  </div>
</div>

我需要将guideData信息传输到新表单中。我不想把它放在URL中,因为guideData可能会很长。

我不知道该怎么做。

2 个答案:

答案 0 :(得分:0)

当调用ajax时,它会转到rails服务器并尝试处理请求。由于guideData是一个js变量而不是全局变量,message.html不会看到它。

此外,当浏览器尝试运行ajax时,您可能会出错。数据选项无效。这就像您将data: [1,2,3]传递给$.ajax而且它无效。将其更改为data: { data: guideData },并在messages.html中尝试将guideData更改为<%= params[:data] %>

message.html的另一个重要问题是与

类似的行
<%= hidden_field_tag 'message[guideEmail]', guideData[3] %>

rails无法访问js变量。如果您按照我上面的建议操作,请在此处guideData[3]更改为params[:data][3]

答案 1 :(得分:0)

感谢。

我最终做的只是使用Handlebars。

我在一个API URL中提供了所有相关数据,因此我只需在我的JS中进行一次API调用。

$.ajax({
    url: "/api/pins/"+id,
    type: "GET",
    data: "JSON"
  }).success(function(data){

    var pinTitle = data["pin"]["activity"];
    var pinDescription = data["pin"]["description"];
    var pinLong = data["pin"]["long"];
    var pinLat = data["pin"]["lat"];
    var pinGuideFirstName = data["pin"]["guide_first_name"];
    var pinGuideLastName = data["pin"]["guide_last_name"];
    var pinGuideRating = data["pin"]["guide_rating"];
    var pinGuideEmail = data["pin"]["guide_email"];
    var pinGuideExperience = data["pin"]["guide_experience"];
    var pinGuideAvatar = data["pin"]["guide_avatar"]["avatar"]["url"];

然后我将数据捆绑到哈希对象/变量(pinData)中,并将pinData发送到我的Handlebars模板中。

var pinData = {
        guideFirstName : pinGuideFirstName,
        guideLastName : pinGuideLastName,
        guideEmail : pinGuideEmail,
        guideExperience : pinGuideExperience,
        guideAvatar : pinGuideAvatar,
        guideRating : pinGuideRating,
        pinActivity : pinTitle,
        pinDescription2 : pinDescription,
        userEmail : currentUserEmail,
        userFirstName : currentUserFirstName,
        userLastName : currentUserLastName
      };

var messageHTML = HandlebarsTemplates['messages/index'](pinData);

messageHTML包含原始HTML代码,其中直接注入了Handlebars变量。

然后,当我点击按钮并将messageHTML直接传入其中时,我使用jQuery打开一个弹出窗口。

$( "#messagePinGuideButton" ).on("click", function() {
        $('.popin').html(messageHTML).fadeIn();
      });

非常简单,非常快,非常直接。我喜欢它。