[英]jQuery $.ajax using local JSON data from global variable
I want to use $.ajax
w/ JSON data ( window.jsonData = '{"dataCallback":[{"key":"val"}]})';
我想使用$.ajax
w / JSON数据( window.jsonData = '{"dataCallback":[{"key":"val"}]})';
) stored in global variable inside the same local js document. )存储在同一本地js文档中的全局变量中。 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. 更新:似乎$.ajax()
, $.getJSON()
, $.get()
, $.getScript()
都需要url(可以指向本地或远程文件)作为数据源。
How can I use the global window.jsonData
as the source of data? 如何使用全局window.jsonData
作为数据源?
See: http://jsfiddle.net/Dns2r/ . 请参阅: http : //jsfiddle.net/Dns2r/ 。 Feel free to play around. 随意玩。
Yes, but you've got to eval
the responseText in the Ajax success callback, or use jQuery's built-in support for JSONP. 是的,但是您必须在Ajax成功回调中eval
responseText,或者使用jQuery的JSONP内置支持。
Another StackOverflow question that might help: 另一个可能有助于解决问题的StackOverflow问题:
Basic example of using .ajax() with JSONP? 在JSONP中使用.ajax()的基本示例?
It sounds like you're trying to mock an Ajax request and return local data instead. 听起来您正在尝试模拟Ajax请求并改为返回本地数据。 If that's the case, give MockJax a whirl: 如果是这样,请给MockJax旋转:
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! 希望这就是你所追求的!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.