jquery load specific page / query strings
I have the following working code:
<script>
$(document).ready(function(){
$('#target').click(function() {
$("#success").load("/contacts/person/view/1", function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#error").html(msg + xhr.status + " " + xhr.statusText);
}
});
});
});
</script>
I wish to have a series of l开发者_开发问答inks such as:
<a id="target">a</a>
<a id="target">b</a>
<a id="target">c</a>
Each of which should when clicked bring up a specific person. So each link will reference a particular person. Therefore depending on which link clicked the value of:
/contacts/person/view/1
must change.
How can I do this please?
Thanks for any assistance.
Consider placing the link for the AJAX request inside the A tag's href attribute, <a href="/contacts/person/view/1" class="target">a</a>
. Then you can use Rob W's code below with a slight modification:
<a href="/contacts/person/view/1" class="target">a</a>
<a href="/contacts/person/view/2" class="target">b</a>
<a href="/contacts/person/view/3" class="target">c</a>
<script>
$(document).ready(function(){
$('.target').click(function(e) {
e.preventDefault();
$("#success").load(this.href, function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#error").html(msg + xhr.status + " " + xhr.statusText);
}
});
});
});
</script>
Notice the difference is the URL parameter in load is set to this.href
, this
here refers to the a
tag that was clicked on.
You could assign a data-id
to the <a id="target" data-id="1">a</a>
and then assign the data-id value to a var in your function like so: var personNumber = $(this).attr("data-id");
Your Javascript would then look like this:
<script>
$(document).ready(function() {
$('#target').live('click', function() {
var personNumber = $(this).attr("data-id");
$("#success").load("/contacts/person/view/"+personNumber, function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#error").html(msg + xhr.status + " " + xhr.statusText);
}
});
});
});
</script>
And your html would look like this:
<a href="javascript:void(0);" id="target" data-id="1">a</a>
<a href="javascript:void(0);" id="target" data-id="2">b</a>
<a href="javascript:void(0);" id="target" data-id="3">c</a>
精彩评论