简体   繁体   English

回复javascript与PHP功能里面?

[英]Echo javascript with a php function inside?

Oh boy! 好家伙! I cant get this to work. 我不能让这个工作。 Any ideas on what the heck I'm doing wrong? 关于我做错了什么的任何想法? Here's the code. 这是代码。

I'm trying to echo the script but use a php function to get the directory of the js file!! 我试图回应脚本,但使用PHP函数来获取js文件的目录!

Any help would be appreicated!! 任何帮助都会被贬低!!

echo '<script src="<?php get_some_function();?> . /js/main.js"></script>';

I've tried dif scenerios with escaping but cant get this to output correctly. 我已尝试使用转义的dis scenerios,但无法正确输出。

Since you're already in the PHP context, you can simply concatenate the strings, like so: 由于您已经在PHP上下文中,因此可以简单地连接字符串,如下所示:

echo '<script src="' . get_some_function() . '/js/main.js"></script>';

Using sprintf() looks more cleaner, though: 但是使用sprintf()看起来更干净:

echo sprintf('<script src="%s/js/main.js"></script>', get_some_function());

Instead of opening another script tag inside the string, concat the string and echo. 不是在字符串中打开另一个脚本标记,而是将字符串和echo连接起来。 The <?php within your string will not be evaluated. 不会评估字符串中的<?php

echo '<script src="'. get_some_function() . '/js/main.js"></script>';

Simple string concatenation: 简单的字符串连接:

echo '<script src="' . get_some_function() . '/js/main.js"></script>';

Don't forget to properly escape the output of your function! 不要忘记正确地逃避功能的输出!

try doing this: 试着这样做:

echo '<script src="'.get_some_function().' /js/main.js"></script>';

or this: 或这个:

$value = get_some_function();
echo '<script src="'.$value.' /js/main.js"></script>';

Remember that any variable echoed in single quotes ( ' ' ), the value of that variable will be not printed, and if a variable is echoed in double quotes ( " " ) it will be printed. 请记住,任何以单引号('')回显的变量,不会打印该变量的值,如果变量以双引号(“”)回显,则将打印该变量。

Similar is true for returned data from a function stored in a varaible. 对于来自存储在变量中的函数的返回数据也是如此。 If you are using single quotes, then every php code (variable, or a method call of a class) should be concatenated using dot operator ( . , :P ) . 如果您使用单引号,则应使用点运算符(。,:P)连接每个PHP代码(变量或类的方法调用)。 If you are using double quotes, then no need to use . 如果您使用双引号,则无需使用。 .

Like in all above answers, they have used . 就像上面的所有答案一样,他们已经使用了。 to append the php function call, your code may be fine as below also (not tested by me, so you will need to do adjustment) : 要附加php函数调用,你的代码也可以如下所示(未经我测试,所以你需要做调整):

$src = get_some_function();
echo "<script src=$src/js/main.js></script>";

But please note that it is a best practice to use single quotes for any kind of html etc echoed in php code, because HTML attributes are using double quotes. 但请注意,对于在PHP代码中回显的任何类型的html等使用单引号是最佳做法,因为HTML属性使用双引号。

Hope this will help... 希望这会有所帮助......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM