2015-10-18 58 views
0

我有這一點的PHP代碼:從PHP傳遞數據變量jQuery用戶界面對話框

<?php 
$posts = new Posts(); 

foreach($posts->getPosts() as $post){ ?> 
    <div class="post"> 
     <h3><a class="post-link" data-post-id="<?php echo $post['id']; ?>" href="javascript:void(0)"><?php echo $post['title']; ?></a></h3> 
    </div> 

<?php } ?> 

<div id="insert-answer" title="Add new idea to post"> 
<form id="myForm" action="insertidea.php" method="post"> 
    <fieldset> 
     <p><label for="idea">Your idea:</label> 
      <input type="text" name="idea" class="idea"</p> 
     <p><label for="pic">Have a pic? Paste its URL here! (optional)</label> 
      <input type="text" name="pic" class="pic"></p> 
     <input type="hidden"class="author" name="author" value="<?php echo $_SESSION['google_data']['id']; ?>" /> 
     <input type="hidden"class="forpost" name="forpost" value="<?php echo $post['id']; ?>" /> 
    </fieldset> 
</form> 

我想的帖子ID數據變量傳遞給jQuery用戶界面對話框:

$("#insert-answer").dialog({ 
    autoOpen: false, 
    modal:true, 
    buttons: { 
     "Add idea": function() { 
      var 
       forpost = $(this).data("post-id"), // HOW CAN I GET THIS??? 
       author = $(".author").val(), 
       idea = $(".idea").val(), 
       pic = $(".pic").val(); 

      $.post('insertidea.php',{ 
       forpost: forpost, author: author, idea: idea, pic: pic, action:'joined' 
      });//End Post 

      $(".forpost").val(''); 
      $(".author").val(''); 
      $(".idea").val(''); 
      $(".pic").val(''); 

      $(this).dialog("close"); 
     }, 

     Cancel: function() { 
      $(this).dialog("close"); 
     } 
    } 
}); 

$(".post-link").click(function() { 
    $("#insert-answer").dialog("open"); 
}); 

問題是我主要是一個php女孩,我不太明白我已經檢查過的百萬JS例子。我想要做的是使用post id作爲來自php的變量,我可以反過來在我的對話框中通過發佈發送給另一個php腳本。

回答

1

你可以改變你的鏈接後的功能如下:

$(".post-link").on('click', function() { 
    var postid = $(this).data("post-id"); 
    var answer = $("#insert-answer"); 
    $(answer).data('post-id', postid); 
    $(answer).dialog("open"); 
}); 

然後搶在"Add idea": function() {部分有:

var forpost = $("#insert-answer").data("post-id"), 
    author = $(".author").val(), 
    idea = $(".idea").val(), 
    pic = $(".pic").val(); 

所以,你正在做的是基本上保存當前post-id什麼到#insert-answer並從您的對話框中獲取它。這是你以後的事嗎?

更新代碼:@charlietfl是絕對正確的,var post-id是不正確的,我編輯了變量的名稱。

+0

當我聲明post-id(缺少分號?)時,出現某種語法錯誤,我仍在測試這個,非常感謝! – Barbarah

+0

我已經更新了答案。 – Jan

+0

這就是我得到的: SyntaxError:missing;在陳述之前 var post-id = $(this).data(「post-id」); 編輯:它引用函數中的var post-id行,並且phpstorm也在抱怨它。 – Barbarah

相關問題