当用户更改他的选择时,使用 PHP 和 jQuery 更新页面中的标签

Update tag in page, when user changes his selection, with PHP and jQuery

每当用户在 "select html tag" 中更改他的选择时,我需要更新 post 图像。

我正在尝试使用 jQuery 和 php 来做到这一点。

我需要获取用户选择的选项的 ID。

我想用这个 id 来获取图像 url(使用 wordpress 函数)。

最后,我想在图片标签中添加这个 "url"。

这是我的代码:

<script type="text/javascript">
    $(function(){
        $('#select2').select2();

        $('#select2').on('change', function() {
            var country = $('#select2 option:selected').val();
            <?php
            $the_id = 'I NEED HERE ID BY SELCETING IN DROPDPWN';
            $url=wp_get_attachment_url(get_post_thumbnail_id($the_id));
            ?>
            $(".countryvalue").html('<img width="80px" src="<?php echo $url; ?>" />');
        });

    });
</script>

<div class="countryvalue" ></div>

<select id="select2" name="marv_the_author">
      <option value="0">--Select author--</option>
      <option value="100">test</option>
      <option value="101">eeeee</option>
</select>

您应该为此使用 ajax。 更改 jquery 函数以发送 ajax 呼叫, 并创建一个 php 页面来处理该调用并发回正确的 url.

你的 jquery 函数(注意这个页面没有 php 脚本,你可以让它成为一个简单的 HTML 页面):

$(document).ready(function(){
    $('#select2').on('change', function() {
        var country = $('#select2 option:selected').val();
        $.ajax({url: "getImageUrl.php?id=" + country,
                success: function(result){
                    $(".countryvalue").html('<img width="80px" src="' + result + '" />');              
        }});
    });
}); 

像这样创建不同的 php 页面:

<?php
    $id = $_REQUEST["id"];
    $url=wp_get_attachment_url(get_post_thumbnail_id($id));
    echo $url;