1

I'm getting some html content via ajax and on the callback I'd like to get all src paths and convert them into a json. I'm always getting 404 errors, because it loads the images. How can i prepend it from loading? Also, I'm getting the error: Uncaught TypeError: Converting circular structure to JSON

Here's a demo: http://jsfiddle.net/QgFMe/

The only thing i can think of is regex, but i would prefer a non regex solution.

Thanks

CAbbott
  • 8,078
  • 4
  • 31
  • 38
xotix
  • 494
  • 1
  • 13
  • 41
  • I've seen this come up before (but can't find the question) - it seemed that in this case regex was the only viable answer - jQuery does attempt to load the images if you use it to parse the HTML, as you've found. – Alnitak Mar 22 '12 at 15:57

2 Answers2

1

Try:

$(document).ready(function () {
    var pics = [];
    $(this).find("img").each(function () {
        pics.push($(this).attr("src"));                                                                                                                                           
    });

    console.log(pics);

    var json_data = JSON.stringify(pics);

    console.log(json_data);
});
benedict_w
  • 3,543
  • 1
  • 32
  • 49
  • If you are using `map` you can just do it like this: `var pics = $(this).find("img").map(function() { return this.src; });` – Andreas Louv Mar 22 '12 at 16:04
  • if you're going to accumulate yourself you should use `.each()` instead of `.map()`, but the right answer is to use `.map(...).get()` instead. – Alnitak Mar 22 '12 at 16:05
  • @AndreasAL you still need `.get()` too – Alnitak Mar 22 '12 at 16:06
  • hmm, i was sure i tried each and somehow it didn't work. That's why i looked up map. Hmm, but seems at this time, there was some other error. Anyway thanks, I'm going to try it out and reply! – xotix Mar 22 '12 at 16:10
  • @xotix .map() _iterates over an array_ using a _callback_ and _returns_ another jQuery object, but one whose elements are not necessarily DOM elements. `.each()` also iterates using a callback, but then returns the original jQuery object. – Alnitak Mar 22 '12 at 18:00
0

To fix your JSON error, pass the output of .map() to .get().

This converts the pseudo jQuery object returned by .map() into a real array:

var pics = $(this).find("img").map(function () {
    return this.src;                                                                                                                                          
}).get();

NB: $(this).attr('src') === this.src

I don't know a solution to your 404 error though - see comments above.

Alnitak
  • 334,560
  • 70
  • 407
  • 495