views:

243

answers:

1

I'm trying to pull in a filename.txt (contains html) using ajax and change the src path in the data variable before I load it into the target div. If I first load it into the div the browser first requests the broken image and I don't want this so I would like to do my processing before I load anything onto the page.

I can pull the src values fine but I can't change them. In this example the src values aren't changed. Is there a way to do this with selectors or can they only modify DOM elements? Otherwise I may have to do some regex replace but using a selector will be more convenient if possible.

  $.ajax(
  {
     url: getDate+'/'+name+'.txt',
     success: function(data)
     {
        $('img', data).attr('src', 'new_test_src');
        $('#'+target).fadeOut('slow', function(){
           $('#'+target).html(data);

           $('#'+target).fadeIn('slow');
        });

     }
  });

My reason is I'm building a fully standalone javascript template system for a newsletter and since images and other things are upload via a drupal web file manager I want the content creators to keep their paths very short and simple and I can then modify them before I load in the content. This will also be distributed on a CD so I can need to change the paths for that so they still work.

A: 

I think you will need to capture the returned data into a variable before you manipulate anything. Try this:

$.ajax(
  {
     url: getDate+'/'+name+'.txt',
     dataType: "html",
     success: function(data)
     {
        var html = data;
        $('img', html).attr('src', 'new_test_src');
        $('#'+target).fadeOut('slow', function(){
           $('#'+target).html(html);
           $('#'+target).fadeIn('slow');
        });

     }
  });

Also, I would set the dataType option to html just to be on the safe side. Unfortunately, I am unable to test this right now. Another thing to consider is, the manual says this of the returned data:

"html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.

so you could also try wrapping the return data in $() before using any jQuery methods on it, e.g.:

$('img', $(html)).attr('src', 'new_test_src');
karim79
That was the first thing I thought as well but it doesn't work. I also tried all the other possible solutions without any luck. At this point I'm assuming it's just not possible for the selector to manipulate variables.
Blake