I am implementing a callback for a 3rdParty javascript library and I need to return the value, but I need to get the value from the server. I need to do something like this:
3rdPartyObject.getCustomValue = function {
return $.getJSON('myUrl');
}
getJson uses XMLHttpRequest which (I believe) has both synchronous and asynchronous behaviors, can I use the synchronouse behavior?
The getJSON() method is used to get JSON data using an AJAX HTTP GET request.
getJSON( url, [data], [callback] ) method loads JSON data from the server using a GET HTTP request. The method returns XMLHttpRequest object.
Looking at the jQuery source code, this is all $.getJSON
does:
getJSON: function( url, data, callback ) {
return jQuery.get(url, data, callback, "json");
},
And this is all $.get
does:
get: function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
callback = data;
data = null;
}
return jQuery.ajax({
type: "GET",
url: url,
data: data,
success: callback,
dataType: type
});
},
No black magic there. Since you need to customize stuff other than the basic $.getJSON
functionality, you can just use the low-level $.ajax
function and pass the async option as false:
$.ajax({
type: 'GET',
url: 'whatever',
dataType: 'json',
success: function() { },
data: {},
async: false
});
You can also use the following before making your call:
$.ajaxSetup( { "async": false } );
I do not know the scope of the "async" property, I suspect that it is a global config. So consider whether you want to change this back to true after your synchronous call.
example:
3rdPartyObject.getCustomValue = function {
$.ajaxSetup( { "async": false } );
var result = $.getJSON('myUrl');
$.ajaxSetup( { "async": true } );
return result;
}
var jsonObjectInstance = $.parseJSON(
$.ajax(
{
url: "json_data_plz.cgi",
async: false,
dataType: 'json'
}
).responseText
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With