简体   繁体   English

Javascript从单独的PHP脚本获取输出

[英]Javascript get output from separate php script

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变量。

$.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* ). 首先,您需要一个页面/网址来输出您要使用的功能的结果(例如,* 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. 还要记住我说输出 ,而不是返回,因为.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. 现在你有了存储在data_from_ajax中的ajax .get()函数的输出,你可以随意使用它。

$.get() is the right way. $ .get()是正确的方法。

$.get('ajax/test.php', function(data) {
  // use the result
  alert(data);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM