Javascript从单独的PHP脚本获取输出 [英] Javascript get output from separate php script
问题描述
我希望javascript能够使用jQuery调用php脚本(只是回声一个字符串)。
I want javascript to be able to call a php script (which just echos a string) using jQuery.
我认为 $。get
是正确的方法,但不太确定。
I think $.get
is the right way, but not too sure.
然后我想将返回的字符串用作javascript变量。
I then want to use the returned string as a javascript variable.
推荐答案
$。get()确实是这样的。
$.get() is the way to go, indeed.
所有,您将需要一个页面/网址,输出您要使用的功能的结果(例如,* www.yoursite.com / test_output.php *)。您应该创建该页面并调用要在其中使用的功能。
还要记住,我说输出,而不是返回,因为.get将获取http响应的输出,而不是php函数的返回值。
First of all, you will need a page / url that outputs the result of the function you want to use (for example, *www.yoursite.com/test_output.php* ). You should create that page and call the function you want to use there. Also keep in mind that I said output, not return, because .get will fetch the output of the http response, not the returned value of the php function.
因此,如果您在站点中定义了以下功能(当然也可以在test_output.php中定义它):
So if you have the following function defined in your site (you can also define it in test_output.php, of course):
<?php
function say_hello() {
return 'hello world';
}
?>
在test_output.php中,你需要这样的东西:
In test_output.php, you will need something like this:
<?php
echo say_hello();
?>
然后在客户端,你需要一些JavaScript / jQuery:
Then on the client side, you need some JavaScript / jQuery:
var data_from_ajax;
$.get('http://www.yoursite.com/test_output.php', function(data) {
data_from_ajax = data;
});
现在你有了存储在data_from_ajax中的ajax .get()函数的输出,你可以使用它如你所愿。
Now you have the output of the ajax .get() function stored in data_from_ajax and you can use it as you please.
这篇关于Javascript从单独的PHP脚本获取输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!