如何使用jquery在不重新加载所有页面的情况下创建链接


how make link without reload all page with jquery

我想创建一些像facebook这样的页面来加载数据,而不需要更改页面/页眉或页脚中的聊天栏。我知道我可以使用这个代码:

$(function() {
  $("a.load").click(function (e) { 
    e.preventDefault();
    $("#content").load($(this).attr("href"));
  });
});

但我有一个问题。我想给jQuery提供类似的附加数据。

<a href="http://mysite.com/profile123" //for example send-more-data="its-profile-link" //and send even more data like: even-more-data="ID:12235663">go to this profile</a>

所以我可以用这个做更多的事情,比如:

if (send-more-data=="its-profile-link") {
  $id = even-more-data="ID:12235663" //posted on link with jquery
  mysql_Query("select * from users where id =  $id")
}
elseif {
//////
}

所以我可能会在课堂或其他地方发送更多带有ID的数据?请给我举个例子。告诉我使用.load()还是$.ajax()更好?

您可以将get-params传递到链接:

    $(function(){
        $("a.load").click(function (e) { 
            e.preventDefault();
            $("#content").load($(this).attr("href")+"?data1="+$(this).attr("some-data")+"&data2="+$(this).attr("some-more-data"));
        });
    });

你可以使用更好的-强大的AJAX:

    $(function(){
            $("a.load").click(function (e) { 
                e.preventDefault();
                var link = $(this).attr("href");
                var param1 = $(this).attr("some-data");
                var param2 = $(this).attr("some-more-data");
                /* //$.post example
                $.post(link, { data1: param1, data2: param2 },function(data) {
                   $("#content").html(data);
                }); */
                //or $.ajax - basically the same thing
                $.ajax({
                  url: link,
                  data: { data1: param1, data2: param2 },
                  success: function(result) {
                    $("#content").html(result);
                  }
                });
            });
        });

然后在php:中

if (@$_REQUEST['data1']=="its-profile-link"){
$id = @$_REQUEST['data2'];
$id = mysql_real_escape_string($id); //or $id = (int)$id; if id is always integer.
   mysql_Query("select * from users where id =  $id")
}
elseif{
//////
}
<a id="my_a" some-data="asd">
console.log($('#my_a').attr('some-data')); // asd

http://api.jquery.com/attr/