开发者

Jquery function creation vs. no library problem

I have code that relies on jquery that works here:

    $(function() {  


 var referrer = document.referrer;
    var dataText = 'client='+client+'&referrer=';
   dataText = dataText + referrer;

    // Create the AJAX request  
    $.ajax({  
        type: "GET",                   
        url: "http://www.myurl.com/project/thecollector.php",            
        data: dataText,                  
        success: function() {            
            $('#complete').html( 'Your page view has been added!' );  
        }  
    });  
});

I have rewritten the code to not need jquery here:

window.addEventListener('domready', function()
{
 var referrer = document.referrer; 
    var dataText = 'client='+client+'&referrer=';  
   dataText = dataText + referrer;

 if (window.XMLHttpRequest)        
 {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp = new XMLHttpRequest();       
 }
 else        
 {
  // code for IE6, IE5
  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");        
 }
 var url = "http://www.myurl.com/project/thecollector.php?"+dataText;        
 xmlhttp.open("GET",url,false);        
 xmlhttp.send(null);       
});

The problem I am having is that the jquery code always captures the infor开发者_开发知识库mation to the server I am looking for, but the latter only captures it every once and a while, and it feel seemingly random. Is there any way to have a function call to force it, and I tried onload and it doesn't work either.


"domready" is not an event, so I'm surprised this works at all. For instance, in Mozilla and Opera it should be DOMContentLoaded. Are you sure it's not working just because sometimes document.referrer is empty and sometimes it is not?

It would be so much simpler if you just put the code in a <script> block (preferably in an external file) and put it just before the closing tag. Then it would run when the DOM is ready, and there's no faffing about with events. That ought to work fine.

Finally, this looks like it would be best done on the server side, as with something like PHP you can also access the HTTP referrer. Then you can just output the result straight into the HTML. Plus you allow that odd user out there using NoScript or just browsing without JavaScript to see this content.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜