开发者

jquery: Why is this not working on Chrome?

<script> 
$(document).ready(function () {
    $('#enter').click(function() {
    $.post('setCookie.php');
    });     
});
</script> 

<div id="enter"> 
    <a href="http://www.mydomain.com">Enter</a> 
</div> 

When clicking enter, it is supposed to go to mydomain.com and 开发者_JAVA百科also set a cookie. It is working in Firefox, but not IE or Chrome. Any ideas?


It may be going to the site before it loads for Chrome. You could set a target attribute to "_blank" on the anchor tag, or you could use a callback function after $.post finishes, like so:

<script> 
$(function(){
    $('#enter').click(function() {
    $.post('setCookie.php',function(){
window.location = $('#enter a').attr('href');
});
    });     
});
</script> 

<div id="enter"> 
    <a href="http://www.mydomain.com" onclick="return false;">Enter</a> 
</div> 


Try this

$(document).ready(function () {
    $('#enter a').click(function(e) {
       e.stopPropagation();
       var href = this.href;
       $.post('setCookie.php', function(){
          window.location.href = href;
       });
    });     
});


Try with

$('#enter a').click(function() {

Edit: You have a POST going on the anchor click and then a GET with the anchor itself. That seams to be clashing on the browser.

For better results, create a SetCookieAndRedirect.php page and perform the redirect to the url after setting the cookie.


Remember that the .post() call is asynchronous so the rest of the function will continue to flow with the .post() working in the background. You will need to use a callback function inside your post: If you don't want error checking you can skip the if/else and just call the redirect.

$(document).ready(function() {
    $.post('ajax/test.html', function(data) {

      if (data.success === 'cookieset')
      {
          // redirect to page
              window.location.replace("http://mydomain.com");
      }
      else
      {
          // put some sort of notification here that it wasn't set and decide what to do next
              window.location.replace("http://mydomain.com");
      }

    });
});

as far as the redirect you can use either:

to simulate an http redirect use

window.location.replace("http://mydomain.com");

or simulates clicking on a link use

window.location.href = "http://mydomain.com";


I'd do

<a href="javascript:$.post('setCookie.php');window.location='http://www.mydomain.com'">abc</a>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜