在 JavaScript 中使用 php [英] use php inside JavaScript

查看:25
本文介绍了在 JavaScript 中使用 php的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个发送到 PHP 文件的 ajax 函数.现在因为我使用的是 WordPress,所以我可以使用 get_url 函数,所以我不需要对整个 URL 进行硬编码.

I have an ajax function that post to an PHP file. Now since I'm using WordPress I can use the get_url function so I don't need to hard code the entire URL.

WordPress 函数是一个 PHP,所以我试图在 ajax 帖子中使用 PHP.但它不会成功.有任何想法吗 ?有可能吗?

The WordPress function is an PHP so I'm trying to use PHP inside the ajax post. But it wont do the trick. Any ideas ? and is it possible ?

这就是我所拥有的.

$(document).ready(function(){

$('#submit').click(function(){

$.post('<?php echo get_template_directory_uri(); ?>/send.php', $("#mycontactform").serialize(),  function(response) {
$('#success').html(response);
//$('#success').hide('slow');
});
return false;

});

});

我也试过在这样的引号内使用 php echo.

I have also tried the php echo inside quotes like this.

   $.post(' "<?php echo get_template_directory_uri(); ?>" /send.php' ....

我得到这条路的以太方式

ether way I get this path

http://mysite.com/%27%3C?php%20echo%20get_template_directory_uri();%20?%3E%27/send.php&email=&message=&name=&sent=1

推荐答案

Javascript to PHP = nope you can't embed javascript to php, only php can embed html and javascripts.

Javascript to PHP = nope you cant embed javascript to php, only php can embed html and javascripts.

更好的方法是创建一个 .php 文件并在那里插入 javascript...

the better way to do it is to create a .php file and insert the javascript there...

示例:js.php

<?php
    function doSubmit() {
        ?>
        <script>
            $('#submit').click(function(){
                $.post('<?php echo get_template_directory_uri(); ?>/send.php', $("#mycontactform").serialize(), function(response) {
                    $('#success').html(response);
                    //$('#success').hide('slow');
                    });
                return false;
            });
        </script>
        <?php
    }
?>

使用include(js.php);"调用js.php并调用另一个php内部的函数

call the js.php using "include(js.php);" and call the functions inside another php

在你的 index.php 中

<?php
include('js.php');
?>
<html>
    <head><script><?php doSubmit();?></script></head>
    <body>
    </body>
</html>

这篇关于在 JavaScript 中使用 php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆