As far as PHP is concerned (or really, a web server in general), an HTML page is nothing more complicated than a big string.
(就PHP而言(或者说实际上是一般的Web服务器),HTML页面只不过是一个大字符串而已。)
All the fancy work you can do with language like PHP - reading from databases and web services and all that - the ultimate end goal is the exact same basic principle: generate a string of HTML*.
(您可以使用PHP之类的语言完成所有花哨的工作-从数据库和Web服务中读取信息以及所有这些-最终目的是完全相同的基本原理:生成HTML *字符串。)
Your big HTML string doesn't become anything more special than that until it's loaded by a web browser.
(大的HTML字符串在通过网络浏览器加载之前不会变得比它更特别。)
Once a browser loads the page, then all the other magic happens - layout, box model stuff, DOM generation, and many other things, including JavaScript execution.(一旦浏览器加载页面, 则所有其他的魔法发生-布局,盒模型的东西,DOM生成,并且很多其他的东西,包括JavaScript执行。)
So, you don't "call JavaScript from PHP", you "include a JavaScript function call in your output".
(因此,您不必“从PHP调用JavaScript”,而应“在输出中包括JavaScript函数调用”。)
There are many ways to do this, but here are a couple.
(有很多方法可以做到这一点,但是这里有几个。)
Using just PHP:
(仅使用PHP:)
echo '<script type="text/javascript">',
'jsfunction();',
'</script>'
;
Escaping from php mode to direct output mode:
(从php模式转为直接输出模式:)
<?php
// some php stuff
?>
<script type="text/javascript">
jsFunction();
</script>
You don't need to return a function name or anything like that.
(您无需返回函数名称或类似名称。)
First of all, stop writing AJAX requests by hand.(首先,停止手动编写AJAX请求。)
You're only making it hard on yourself.(您只会让自己受苦。)
Get jQuery or one of the other excellent frameworks out there.(获得jQuery或其他出色的框架之一。)
Secondly, understand that you already are going to be executing javascript code once the response is received from the AJAX call.
(其次,了解一旦收到AJAX调用的响应,您已经将要执行javascript代码。)
Here's an example of what I think you're doing with jQuery's AJAX
(这是我认为您正在使用jQuery的AJAX的示例)
$.get(
'wait.php',
{},
function(returnedData) {
document.getElementById("txt").innerHTML = returnedData;
// Ok, here's where you can call another function
someOtherFunctionYouWantToCall();
// But unless you really need to, you don't have to
// We're already in the middle of a function execution
// right here, so you might as well put your code here
},
'text'
);
function someOtherFunctionYouWantToCall() {
// stuff
}
Now, if you're dead-set on sending a function name from PHP back to the AJAX call, you can do that too.
(现在,如果您对将函数名从PHP发送回AJAX调用感到困惑,也可以这样做。)
$.get(
'wait.php',
{},
function(returnedData) {
// Assumes returnedData has a javascript function name
window[returnedData]();
},
'text'
);
* Or JSON or XML etc.
(*或JSON或XML等。)