最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript get output from separate php script - Stack Overflow

programmeradmin4浏览0评论

I want javascript to be able to call a php script (which just echos a string) using jQuery.

I think $.get is the right way, but not too sure.

I then want to use the returned string as a javascript variable.

I want javascript to be able to call a php script (which just echos a string) using jQuery.

I think $.get is the right way, but not too sure.

I then want to use the returned string as a javascript variable.

Share Improve this question edited Oct 11, 2011 at 14:42 jackJoe 11.1k8 gold badges52 silver badges65 bronze badges asked Oct 11, 2011 at 14:13 joedborgjoedborg 18.4k33 gold badges87 silver badges122 bronze badges 1
  • You are looking for Ajax; $.get() and the other Ajax functions in jQuery are indeed the right way. – Pekka Commented Oct 11, 2011 at 14:15
Add a comment  | 

2 Answers 2

Reset to default 16

$.get() is the way to go, indeed.

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.

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';
}
?>

In test_output.php, you will need something like this:

<?php
echo say_hello();
?>

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;
});

Now you have the output of the ajax .get() function stored in data_from_ajax and you can use it as you please.

$.get() is the right way.

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

评论列表(0)

  1. 暂无评论