0

I want to use $.ajax w/ JSON data (window.jsonData = '{"dataCallback":[{"key":"val"}]})';) stored in global variable inside the same local js document. Is this possible and if so how would I do it?

Update: It seems like $.ajax(), $.getJSON(), $.get(), $.getScript() all require url (which can point to a local or remote file) as the data source.

How can I use the global window.jsonData as the source of data?

See: http://jsfiddle.net/Dns2r/. Feel free to play around.

Steve
  • 4,946
  • 12
  • 45
  • 62
  • If the `window.jsonData =` and `;` are included in the response, then it's a JavaScript response with an [object literal](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#Object_literals) (what JSON got its syntax from). You should be able to request it with [`$.getScript()`](http://api.jquery.com/jQuery.getScript/). – Jonathan Lonowski Jan 07 '14 at 22:13
  • @JonathanLonowski `$.getScript()` requires url as the data source. How can I make it accept the global variable `window.jsonData` as the data source? – Steve Jan 07 '14 at 22:43
  • Can you provide some context to show us why you need to do this? It may be that you are trying to solve a problem that would be better solved another way. – crad Jan 08 '14 at 01:57

2 Answers2

0

Yes, but you've got to eval the responseText in the Ajax success callback, or use jQuery's built-in support for JSONP.

Another StackOverflow question that might help:

Basic example of using .ajax() with JSONP?

Community
  • 1
  • 1
Greg Burghardt
  • 17,900
  • 9
  • 49
  • 92
  • Right, how would I set that up? I'll throw up a jsfiddle for us to play with. Give me a few moments. Thanks for the reply! :) – Steve Jan 07 '14 at 22:03
  • Update: `eval(window.jsonData)` is throwing an error. Unfortunately, `$.ajax()` requires url as the data source. How can I make it accept the global variable `window.jsonData` as the data source? – Steve Jan 07 '14 at 22:41
  • The ajax response needs to be valid JavaScript that declares and populates that variable. – Greg Burghardt Jan 07 '14 at 23:19
0

It sounds like you're trying to mock an Ajax request and return local data instead. If that's the case, give MockJax a whirl:

window.jsonData = '{"dataCallback":[{"key":"val"}]})';

// Set up the mockjax handler
$.mockjax({
  url: '/some/url',
  responseText: window.jsonData
});

// Now call the ajax method of your choice
$.getJSON('/some/url', function (data) {
  console.log(data.dataCallback[0].key); // "val"
});

Hope this is what you're after!

adamesque
  • 1,906
  • 19
  • 24