从 jQuery 调用 PHP 函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3548802/
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
Call PHP function from jQuery?
提问by Brigante
I have a PHP function on my site which takes a couple of seconds to complete. This holds the whole page up which I don't want.
我的网站上有一个 PHP 函数,需要几秒钟才能完成。这会保留我不想要的整个页面。
Would it be possible with jquery to call this PHP function after the page has loaded and display the results in a div? Also to display an ajax loader image until the PHP function has completed?
在页面加载并在 div 中显示结果后,jquery 是否可以调用这个 PHP 函数?还要显示 ajax 加载程序图像,直到 PHP 函数完成?
I've been looking at jQuery.post but can't seem to get it to work.
我一直在看 jQuery.post 但似乎无法让它工作。
Would someone be able to help?
有人可以帮忙吗?
Thank you
谢谢
回答by Otar
AJAX does the magic:
AJAX 发挥了神奇的作用:
$(document).ready(function(
$.ajax({ url: 'script.php?argument=value&foo=bar' });
));
回答by Brigante
Thanks all. I took bits of each of your solutions and made my own.
谢谢大家。我从你的每一个解决方案中汲取了一点点并制作了我自己的。
The final working solution is:
最终的工作解决方案是:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: '<?php bloginfo('template_url'); ?>/functions/twitter.php',
data: "tweets=<?php echo $ct_tweets; ?>&account=<?php echo $ct_twitter; ?>",
success: function(data) {
$('#twitter-loader').remove();
$('#twitter-container').html(data);
}
});
});
</script>
回答by hookedonwinter
Yes, this is definitely possible. You'll need to have the php function in a separate php file. Here's an example using $.post:
是的,这绝对是可能的。您需要在单独的 php 文件中包含 php 函数。下面是一个使用 $.post 的例子:
$.post(
'yourphpscript.php', // location of your php script
{ name: "bob", user_id: 1234 }, // any data you want to send to the script
function( data ){ // a function to deal with the returned information
$( 'body ').append( data );
});
And then, in your php script, just echo the html you want. This is a simple example, but a good place to get started:
然后,在您的 php 脚本中,只需回显您想要的 html。这是一个简单的例子,但是一个很好的开始:
<?php
echo '<div id="test">Hello, World!</div>';
?>
回答by Palantir
This is exactly what ajax is for. See here:
这正是 ajax 的用途。看这里:
Basically, you ajax/test.php and put the returned HTML code to the element which has the result id.
基本上,您 ajax/test.php 并将返回的 HTML 代码放入具有结果 ID 的元素。
$('#result').load('ajax/test.php');
Of course, you will need to put the functionality which takes time to a new php file (or call the old one with a GET parameter which will activate that functionality only).
当然,您需要将需要时间的功能放到一个新的 php 文件中(或者使用 GET 参数调用旧的,该参数只会激活该功能)。