Why is the return false stopping the alert?
Why does the return false
stop the alert()
from working and how do I get around this? If I remove it, the alert will show up, and then it will load the page that the <a>
tag pointed to.
<script type="text/javascript">
$("docume开发者_如何学Pythonnt").ready(function(){
$("a").click(function(){
if(!$(this).is('static')){
var href = $(this).attr('href');
$.getJSON(href, function(data) {
alert('hi');
});
}
return false;
});
});
</script>
My guess is that badly formed JSON is being sent to the client, which will prevent the callback from firing. The manual says:
If there is a syntax error in the JSON file, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason.
Can you show us a snapshot of the JSON that the server is generating?
Answer Update!
I have tested this thoroughly using the $.ajax functions, which is what actually gets called by $.getJSON.
$("document").ready(function(){
$("a").click(function(event){
if(!$(this).is('static')){
var href = $(this).attr('href');
$.ajax({
url: href,
dataType: 'text',
success: function(data) {
alert("hi");
}
});
}
return false;
});
});
With a correctly formatted JSON object, this works as expected. Here is the contents of my json.html test file:
{ "firstName" : "John",
"lastName" : "Doe",
"age" : 23 }
However, if the file contains HTML, or a badly formatted JSON object, the alert never gets called - in fact, by adding an error handler to the above example, you'll spot that it errors:
$("document").ready(function(){
$("a").click(function(event){
if(!$(this).is('static')){
var href = $(this).attr('href');
$.ajax({
url: href,
dataType: 'text',
success: function(data) {
alert("hi");
},
error: function() {
alert("NO!!!!");
}
});
}
return false;
});
});
As you are replacing hyperlinks in your code with this request, I'm guessing that you maybe want to use a $.get, rather than a $.getJSON. So to return to your original example:
<script type="text/javascript">
$("document").ready(function(){
$("a").click(function(){
if(!$(this).is('static')){
var href = $(this).attr('href');
$.get(href, function(data) {
alert('hi');
});
}
return false;
});
});
</script>
This seems to work in Firefox 3 and in Chrome, with both get and getJSON.
IE8 is another story (I presume the same goes for IE7). There, only get works; getJSON fails. Is the JSON being returned by the server not IE-friendly?
精彩评论