返回"成功:"方法的数据?方法、数据、QUOT

2023-09-10 20:05:35 作者:動了情,傷了心

我试图让一个实用方法的返回值,我写了使用jQuery:

I'm trying to get the return value of a utility method I wrote using jquery:

function loadFrames(coords, spritesheet) {
    return $.ajax({
        type: "GET",
        url: coords,
        dataType: "xml",
        success: function(xml,code,obj) {return parseFrameData(xml, spritesheet);}
    });
}

所以,这个方法接收两个参数,打开一个文件(一个由plist中的说法指出,)并运行parseFrameData方法。 后者将返回对象的数组。

So, this method receives two arguments, opens a file (the one pointed to by the "plist" argument) and runs the parseFrameData method. The latter returns an array of objects.

我想用这种方式如下:

var frames = loadFrames('player.xml', 'spritesheet.png');

但我没有找到的方式说回报你叫上线起点与方法的价值的成功:...

but I don't find the way to say "return the value of the method you called on line starting with "'success:' "...

推荐答案

编辑:的answer发布到@Tomalak链接告诉我这个很酷的'承诺',你可能也想看看的概念。问题

An answer posted to the question @Tomalak linked to informed me of this cool concept of 'Promises', which you might also want to take a look at.

使用$阿贾克斯的点一般是让同步的请求。调用它和期待值,以立即返回将是一个同步的要求。

The point of using $.ajax is generally to make asynchronous requests. Calling it and expecting a value to be returned immediately would be a synchronous request.

话虽这么说,你可以通过设置你要问在同步模式下使用$就什么异步:假。这可能会锁定您的浏览器,直到请求完成的影响。

That being said, you can do what you're asking by using $.ajax in synchronous mode by setting async:false. This may have the affect of locking your browser until the request completes.

function loadFrames(coords, spritesheet) {
  var myFrames;

  $.ajax({
    type: "GET",
    url: coords,
    dataType: "xml",
    async: false,
    success: function(xml,code,obj) {myFrames = parseFrameData(xml, spritesheet);}
  });
  return myFrames;
}

var frames = loadFrames('player.xml', 'spritesheet.png');

我相信这是将工作,但我没有测试它的好方法。任何人都可以证实这一点的方法吗?

I believe that is will work, but I don't have a good way to test it. Can anyone else confirm this approach?

不过这将是更好的做到这一点异步@Petah暗示的方式。

Still it would be much better to do this asynchronously the way @Petah suggests.