php 使用jQuery的ajax get请求带参数,返回页面内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2892070/
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
Using jQuery's ajax get request with parameters, returning page content
提问by NickKampe
I'm trying to use jQuery's get function to call my php script. The php script returns a variable containing the built template of the main content of my page minus my static header/footer.
我正在尝试使用 jQuery 的 get 函数来调用我的 php 脚本。php 脚本返回一个变量,其中包含我的页面主要内容的构建模板减去我的静态页眉/页脚。
I would like to use the returned content to replace the "old" page content without the page reloading. Can anyone point me in the right direction as to where I'm going wrong here? My code is as follows...
我想使用返回的内容来替换“旧”页面内容而无需重新加载页面。任何人都可以指出我在这里出错的正确方向吗?我的代码如下...
jQuery:
jQuery:
function getData(time, type) {
$.ajax({
type: "GET",
url: "getData.php",
data: "time=" + time + "&type=" + type,
success: function(data){
$('#pageContent').fadeOut("slow");
$('#pageContent').html(data);
$('#pageContent').fadeIn("slow");
}
});
return false;
}
getData.php(paraphrased):
getData.php(释义):
....
$time = empty($_GET['time']) ? '' : $_GET['time'];
$type = empty($_GET['type']) ? '' : $_GET['type'];
echo getData($time, $type);
function getData($time, $type)
......
.....
$tmpl = new Template();
$tmpl->time= $time;
$tmpl->type = $type;
$builtpage = $tmpl->build('index.tmpl');
return $builtpage;
.....
......
jQuery function call:
jQuery 函数调用:
<a href="#" onclick="getData('<?php print $tmpl->time; ?>', 'Orange')">Orange</a>
<a href="#" onclick="getData('<?php print $tmpl->time; ?>', 'Apple')">Apple</a>
<a href="#" onclick="getData('<?php print $tmpl->time; ?>', 'Banana')">Banana</a>
When I click any link, the ajax seems to run fine, and the page does refuse to reload, but the content still remains unchanged... Anyone happen to know what's up?
当我单击任何链接时,ajax 似乎运行良好,并且页面确实拒绝重新加载,但内容仍然保持不变......有人碰巧知道发生了什么吗?
回答by
First in the successfunction, check to make sure that you are receiving what you are looking for:
首先在success函数中,检查以确保您收到了您要找的东西:
success: function(data){
alert(data);
}
Also in the php file, try putting this on top of the script:
同样在 php 文件中,尝试将其放在脚本的顶部:
header("Content-Type: text/html");
And try modifying your code like:
并尝试修改您的代码,如:
success: function(data){
$('#pageContent').html(''); // remove what was before
$('#pageContent').fadeOut("slow");
$('#pageContent').html(data);
$('#pageContent').fadeIn("slow");
}

