php怎么触发js函数,如何从PHP调用JavaScript函数?

mithunsatheeshZeeshan Rang提出了一个问题:How to call a JavaScript function from PHP?,或许与您遇到的问题类似。

回答者Peter Bailey给出了该问题的处理方式:

As far as PHP is concerned (or really, a web server in general), an HTML page is nothing more complicated than a big string.

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*.

Your big HTML string doesn't become anything more special than that until it's loaded by a web browser. 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.

So, you don't "call JavaScript from PHP", you "include a JavaScript function call in your output".

There are many ways to do this, but here are a couple.

Using just PHP:

echo '

'jsfunction();',

''

;

Escaping from php mode to direct output mode:

// some php stuff

?>

jsFunction();

You don't need to return a function name or anything like that. First of all, stop writing AJAX requests by hand. You're only making it hard on yourself. Get jQuery or one of the other excellent frameworks out there.

Secondly, understand that you already are going to be executing javascript code once the response is received from the AJAX call.

Here's an example of what I think you're doing with jQuery's 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 do

// 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.

$.get(

'wait.php',

{},

function(returnedData) {

// Assumes returnedData has a javascript function name

window[returnedData]();

},

'text'

);Or JSON or XML etc.

希望本文对你有帮助,欢迎支持JavaScript中文网

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值