如何在jQuery函数中使用php值

时间:2018-01-05 00:51:43

标签: php jquery

我有一个php文件,里面有一个脚本。

我正在尝试通过php(the_main_image)调用一个图像,并使用jQuery在此图像前面添加一组链接(以及当前正常工作的图标)。这是我到目前为止所做的,但它目前打破了这个功能

<script>
    jQuery(document).ready(function($) {

        $("#lesen").click(function() {

            var bla = $('#my_hidden_input').val();
            var test = "<?php the_main_image(); ?>";

        $.ajax({
            url: bla,
            dataType: "text",
            success: function(data) {
                $(".text").html(data);
                $(".text a[href^='http']").each(function() {

                    $(this).prepend(test);
                    $(this).prepend('<img src="https://www.google.com/s2/favicons?domain=' + this.href + '">');



                });
            }
        });
    });

});
</script>

如何在prepend或其他类似的jQuery函数中使用包含php的jQuery var值?

3 个答案:

答案 0 :(得分:1)

您好我在我的项目中做了类似的事情,下面为我工作。

由于您无法直接在JavaScript中编写php,因此需要获取html的帮助。

在您的html中创建一个隐藏的输入字段,如下所示

<input type="hidden" id="something" value="<?php the_main_image(); ?>"/>

然后在jquery中阅读

<script>
    jQuery(document).ready(function($) {

        $("#lesen").click(function() {

            var bla = $('#my_hidden_input').val();
            var test = $("#something").val();

        $.ajax({
            url: bla,
            dataType: "text",
            success: function(data) {
                $(".text").html(data);
                $(".text a[href^='http']").each(function() {

                    $(this).prepend(test);
                    $(this).prepend('<img src="https://www.google.com/s2/favicons?domain=' + this.href + '">');



                });
            }
        });
    });

});
</script>

希望这会有所帮助。

答案 1 :(得分:1)

如果你在php中的函数没有回显结果。尝试添加回声。 <?php echo the_main_image(); ?>。好像你忘了回应结果。

P.S。你可以从php渲染结果,甚至在放在php文件中的js代码中使用它,但是你应该记住mixin php和js是不好的做法,应该小心翼翼地完成。

它是如何工作的:php解释器在向用户发送静态html之前读取你的文件并解释<?php ?>内所有与php相关的鳕鱼,如果你回应它会在你执行此操作的那一行中显示的内容(或调用函数而不是回声)。正如有人提到的,如果你用引号回显字符串,如果你在相同类型的引号中内嵌你的php标签,它可以打破js。

答案 2 :(得分:0)

尝试使用ajax在jquery funcion中获取php值。