javascript - 将数据变量从 PHP 传递到 jquery ui 对话框

标签 javascript php jquery jquery-ui

我有这段 php 代码:

    <?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>

我想将 post id 数据变量传递到 jquery ui 对话框:

    $( "#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 的变量,我可以在对话框中使用它通过 post 发送到另一个 php 脚本。

最佳答案

您可以按如下方式更改链接后功能:

$( ".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 不正确,我已经编辑了变量的名称。

关于javascript - 将数据变量从 PHP 传递到 jquery ui 对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33203316/

相关文章:

php - 使用 php 变量来操作 html 的标题和正文的 Id (有人这样做吗?)

javascript - 如何提醒用户输入类型文本在用户输入时检测到点?

javascript - 检查子对象是否存在,如果存在,则添加到对象

javascript - 同位素 - 单击以展开图像并在左上角定位

javascript - 关于在 Node 中使用流读取数据

javascript - 使用 php/mysql/js 创建流程图/图表

java - php 中的变量不会显示在 android 上(使用 json)

jQuery - 搜索对象数组以按对象属性进行过滤

javascript - 在javascript中从纬度和经度获取邮政编码

javascript - 选择下拉菜单中的列表时使 div 消失