开发者

jquery trouble with getJSON call

Got some basic problem again.

I need to modify a function that previously returned a in code written object. Im now trying to get the object from json through $.getJSON

function getEventData() {
  var result = '';

  $.getJSON("ajax.php?cmd=getbydate&fromdate=&todate=", function(data) {
    result = data;
  });
  return result;
}

Problem is that result isn't set in the callback function for obvious reasons.

Do you guys have a solution for this?

Edit: Ok i got an answer that was removed. I j开发者_如何学Cust had to change it abit..

This is the answer that works:

function getEventData() {
  var result = '';
  url = "ajax.php?cmd=getbydate&fromdate=&todate=";
  $.ajax({
    url: url,
    async: false,
    dataType: 'json',
    success: function(data) {
      result = data;
    }
  });
  return result;
}


You should program your application in an asynchronous way, which means, that you should use callback functions for you application flow, too, or continue in the getJson callback function. You can also make the request synchronously which should then be able to return the value (or at least assign it and block the function till the callback is completed), but this is not recommended at all:

function getEventData() {
  var result = '';

  result = $.ajax({
    url: "ajax.php?cmd=getbydate&fromdate=&todate=",
    async: false,
    dataType: "json",
    data: data,
    success: function(data) {
      return data;
    }
  });
  return result;
}


Are you sure that the server returns valid json? It will be better to validate it using a tool like jsonlint. Also make sure that application/json is used as content type for the response.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜