简体   繁体   English

如何通过sprintf()将PHP参数传递给javascript函数?

[英]How do I pass PHP parameters through an sprintf() to a javascript function?

I have been charged with taking over a project to develop a web tool/interface for a proprietary bit of software. 我负责执行一个项目,以开发用于专有软件的Web工具/界面。 The current sticking point is (using the established practices / patterns) to perform a connection test to the server based upon values entered by the user. 当前的症结是(使用已建立的实践/模式)根据用户输入的值执行到服务器的连接测试。

Currently, there is a sub-menu formatted with an sprintf(). 当前,有一个用sprintf()格式化的子菜单。 I have attempted various methods to pass the parameters, but the receiving JavaScript funciton fails. 我尝试了各种方法来传递参数,但是接收JavaScript函数失败。

The submenu: 子菜单:

$submenu = sprintf('<div id="Menu"><ul id="ControlSubMenu">%s</ul></div>',
                '<li><a href="#inner_content" class="TestConn" id="TestConn" onClick="testpbxconnection($ct_host, $ct_port, $ct_un, $ct_pw);return false;">Test Connection</a></li>
 <li> <a href="#inner_content" class="EditConn" id="EditConn" onClick="editpbxconnection();return false;">Edit Connection</a></li>');

The receiving JS function, in another file: 接收JS函数,在另一个文件中:

function testconnection(a, b, c, d)
{   alert('Test Function Hit.');
alert('Host: ' + a);
alert('Port: ' + b);
alert('User Name: ' + c);
alert('Password:' + d);
}

Am I even on the right track? 我是否在正确的轨道上? Any assistance will be greatly appreciated. 任何帮助将不胜感激。

There are a few problems here, sprintf is used for variable substitution in strings, which is being done kind of oddly by passing in a string with variables as a parameter. 这里有一些问题, sprintf用于字符串中的变量替换,这是通过传入以变量为参数的字符串来完成的。 You also aren't quoting your javascript variables, which will cause an error. 您也没有引用JavaScript变量,这将导致错误。 Additionally, your function names aren't the same testpbxconnection vs. testconnection . 此外,您的函数名称与testpbxconnectiontestconnection Your sprintf call should look more like: 您的sprintf调用应类似于:

$submenu = sprintf('<div id="Menu">
       <ul id="ControlSubMenu">
         <li>
            <a href="#inner_content" class="TestConn" id="TestConn" onClick="testconnection(\'%s\', \'%s\', \'%s\', \'%s\');return false;">Test Connection</a>
         </li>
         <li> 
            <a href="#inner_content" class="EditConn" id="EditConn" onClick="editpbxconnection();return false;">Edit Connection</a>
         </li>
       </ul>
     </div>', $ct_host, $ct_port, $ct_un, $ct_pw);
you should pass parameter as an argument while calling a function

    $demo = "Hello";
    <input type="text" onclick="return demoFunction(<?php echo $demo; ?> );"/>
    more references
    http://www.webdeveloper.com/forum/showthread.php?147162-pass-php-variable-to-javascript-function 

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

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