我正在尝试从查询字符串中获取数据,但将其与Ajax一起使用。 我似乎无法正确传递数据,我想知道我的语法错误在哪里:
$(function()
{
$("#link").click(function(event)
{
event.preventDefault();
$.get("request.php",{id:+link.attr('id')},function(response){
$("#ajaxresponse div").fadeOut("fast", function()
{
$("#ajaxresponse div").remove();
$("#ajaxresponse").append($(response).hide().fadeIn());
});
}
});
return false;
});
});
html页面代码:
<div class="content">
<a href="request.php?id=1" id="link">
</div>
我没有正确地将数据结构化为ajax调用吗?
提前致谢
我可以让它正确返回,但不是以Ajax方式,它仍然加载.php页面而不是附加它,这里是request.php方面的事情:
$username = $_GET['id'];
echo getTemplate($username);
function getTemplate($username)
{
return '<div class="box">
<h1>ID is</h1>
<div class="meta">username: '.$username.'</div>
</div>';
}
答案 0 :(得分:1)
您可以使用像这样的实用程序功能
function getParameterByName(name,url) {
var match = RegExp('[?&]' + name + '=([^&]*)')
.exec(url);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
然后在你的代码中使用它就像
一样使用它$("#link").click(function(event)
{
event.preventDefault();
var id = getParameterByName('id',$(this).attr('href'));
$.get("request.php",{id:id},function(response){
答案 1 :(得分:0)
{id:+link.attr('id')}
应该是
{ id: link.attr('id') }
答案 2 :(得分:0)
在任何其他功能之外添加此功能:
function getUrlVars(url){
var vars = [], hash;
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++){
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
然后使用:
getUrlVars($(this).attr("href"))["id"]
而不是
link.attr('id')