views:

55

answers:

2

I have this $.ajax (using jquery) code, it originally was the $.get that is now commented but for some reason I'm always getting the error and I can't find anything wrong with it =/, am I overlooking something?

$.fn.randomContent = function(options){
    var contentArray = new Array();
    var dType = "html";
    var defaults = {
     xmlPath: "../xml/client-quotes.xml",
     nodeName: "quote"
    };
    var options = $.extend(defaults, options);
    alert(options);
    $.ajax({
     type: "GET",
     url: "../xml/client-quotes.xml",
     dataType: "html",
     success: function(){
      $(defaults.nodeName).each(function(i){
       contentArray.push($(this).text());
      });
      $(this).each(function(){
       $(this).append(getRandom());
      });
     },
     error: function(){
      alert("Something Went wrong");
     }

    });
    /*$.get(defaults.xmlPath, function(){
              alert("get");
     $(defaults.nodeName).each(function(i){
      contentArray.push($(this).text());
     });
     $(this).each(function(){
      $(this).append(getRandom());
     });
    }, type);//$.get*/
};

Here's the getRandom() function:

function getRandom() {
    var num = contentArray.length
    var randNum = Math.floor(Math.random()*num)
    var content = "";
    for(x in contentArray){
     if(x==randNum){
      content = contentArray[x];
     }
    };
    alert(content);
    return content;
}
A: 

Does that url have to be absolute? I've never tried doing ajax requests with a "../" in it. Do you have FireBug installed? You could examine the response header from the sever.

ScottyUCSD
it doesn't matter I've tried it without the ../ and still won't work. Yes I have FireBug installed and I don't get any response header whatsoever...I have no idea why though.
Luis Armando
+1  A: 

It could be that the browser is caching your GET requests. In this case, either:

  1. ensure the server is controlling your cache options (using cache-control settings of private or no-cache)
  2. change the method of your AJAX call to POST instead of GET
  3. differentiate your GET request by adding querystring parameters that change with each request

I prefer option #1, specifically because POST operations are intended to change something on the server, and so we should use that method when our actions do in fact modify server state. GET requests on the other hand, are requests that do nothing more than read data.

I feel a GET request is more appropriate for this task, and so in my own code I would prevent the caching of the response.

David Andres