Returning data from ajax results in strange object

I know this question hast probably been asked a thousand times, but i cannot seem to find the answer. I want result to be the data returned from the ajax-request, which should be a json-data array (the result of console.log(data) ).

  var result = $.ajax({
    type: 'GET',
    url: dataPath,
    dataType: 'json',
    success: function(data) {
      console.log(data)
      },
    error: function(){
      //alert("damn");  
      },
    data: {},
    aync: false
  });

  console.log(result); 

However, console.log(result); will return some strange object, which I don't know how to handle. Why isn't result = data ?


Typo.

Change this:

aync: false

to:

async: false

And the ajax method still returns the jqXHR object doing the request, not the result. Use the data parameter in the success call and store it somewhere.


First of all remove the aync: false from your code. It should be spelled async: false but you don't need it to achieve your goal and what it actually does is block the entire browser's user interface resulting in a terrible user experience. Remember that "A" in AJAX means Asynchronous .

The result of an $.ajax() call is a promise which is not the same as your data, but it can still be useful to get to your data. You just need to use it in a certain way.

Try changing:

 console.log(result);

to:

result.done(function (data) { 
    console.log(data);
});

or:

result.done(function (data) { 
    console.dir(data);
});

or even this might work - untested:

result.done(console.dir);

See this answer for a better explanation.


初始化success函数内的result

 var result;
  $.ajax({
        type: 'GET',
        url: dataPath,
        dataType: 'json',
        success: function(data) {
          result = data;
          console.log(data)
          },
        error: function(){
          //alert("damn");  
          },
        data: {},
        async: false
      });

      console.log(result);
链接地址: http://www.djcxy.com/p/55392.html

上一篇: 为什么有同步和异步模块的规格?

下一篇: 从Ajax返回数据会导致奇怪的对象