javascript Javascript从单独的php脚本中获取输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7727446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript get output from separate php script
提问by joedborg
I want javascript to be able to call a php script (which just echos a string) using jQuery.
我希望 javascript 能够使用 jQuery 调用 php 脚本(它只是回显一个字符串)。
I think $.get
is the right way, but not too sure.
我认为$.get
是正确的方法,但不太确定。
I then want to use the returned string as a javascript variable.
然后我想使用返回的字符串作为 javascript 变量。
回答by agente_secreto
$.get() is the way to go, indeed.
$.get() 确实是要走的路。
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.
首先,您需要一个页面 / url 来输出您要使用的函数的结果(例如, *www.yoursite.com/test_output.php* )。您应该创建该页面并在那里调用您想要使用的函数。还要记住,我说的是output,而不是 return,因为 .get 将获取 http 响应的输出,而不是 php 函数的返回值。
So if you have the following function defined in your site (you can also define it in test_output.php, of course):
因此,如果您在站点中定义了以下函数(当然,您也可以在 test_output.php 中定义它):
<?php
function say_hello() {
return 'hello world';
}
?>
In test_output.php, you will need something like this:
在 test_output.php 中,你需要这样的东西:
<?php
echo say_hello();
?>
Then on the client side, you need some JavaScript / jQuery:
然后在客户端,您需要一些 JavaScript / jQuery:
var data_from_ajax;
$.get('http://www.yoursite.com/test_output.php', function(data) {
data_from_ajax = data;
});
Now you have the output of the ajax .get() function stored in data_from_ajax and you can use it as you please.
现在您将 ajax .get() 函数的输出存储在 data_from_ajax 中,您可以随意使用它。