Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

Call PHP Function using jQuery AJAX

I've read all the topics about my question but cannot solve my problem. I want to get php function result using jQuery AJAX.

function.php

function generateCode() {
//code here
}

function generateResult() {
//code here
}

How can I catch the function result using jQuery AJAX? I don't want to change function.php structure because it related to another pages.

Refer to using jquery $.ajax to call a PHP function, no answer can solve my problem. Thank You

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You cannot call a function in a PHP file from Javascript, full stop. The client (here: Javascript) can only communicate with the server (here: PHP) through the HTTP protocol. The HTTP protocol has no notion of files, functions or programming languages. This means you're limited to transmitting information via the URL or HTTP headers. As such, you can never call a PHP function from Javascript, all you can do is request a URL which returns data.

So, by requesting a URL, say http://example.com/myscript.php, the script myscript.php gets invoked. This script now has to figure out what it should do and output some response. This script can actually call PHP functions, e.g.:

// myscript.php

include 'functions.php'
echo generateCode();

As such, whenever you request the URL http://exmaple.com/myscript.php, you will get the output of the function generateCode(). You may notice that this works the same as when you visit a URL with a web browser. That's because this is the only mechanism to run code through a web server using the HTTP protocol and hence the only way Javascript can "call PHP functions". Javascript has no secret backdoor to call PHP functions directly.

Hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...