getJSON Synchronous

☆樱花仙子☆ 提交于 2019-11-27 13:27:26
tobspr

Asynchronusly does mean the Request is running in the background, and calls your function back when it got a response. This method is best if you want to have a result but allow to use your app within the request. If you want to have a direct response, take a look at a synchron request. this request will pause script execution until it got a response, and the user can not do anything until the response was recieved. You can toggle it via:

async: false,

So for example:

$.ajax({
    url: "myurl",
    async: false,
    ...
})

Since $.getJSON() uses ajax configurations, just set the global ajax configs:

// Set the global configs to synchronous 
$.ajaxSetup({
    async: false
});

// Your $.getJSON() request is now synchronous...

// Set the global configs back to asynchronous 
$.ajaxSetup({
    async: true
});

$.getJSON(), doesn't accept a configuration, as it says in the docs it's a shorthand version of:

$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: success
});

So just rewrite your request in terms of that and async:false will work just as you expect.

$.getJSON() is a shorthand notation for $.ajax() which can be configured to be synchronous (see jQuery.getJSON and JQuery.ajax):

$.ajax({
  dataType: "json",
  url: url,
  data: data,
  async: false, 
  success: function(data) {
      ...
      draw_polygon(data);
  }
});

Try to avoid synchronous calls though. Quote from jQuery doc (see async prop):

Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

You might want to try jQuery Deferreds like this:

var jqxhr = $.getJSON(url);
jqxhr.done(function(data) {
    ...
    draw_polygon(data);
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!