简体   繁体   English

将服务器的json响应克隆到另一个变量中

[英]Cloning the json response from the server into another variable

Hell guys, 地狱伙计们,

I am getting a json response from the PHP script like this: 我从PHP脚本得到一个json响应,如下所示:

 function getAuctionItems() { var copiedObject = {}; var jqxhr = $.post( "php/server.php", {command:'auctions'},function() {}) .done(function(data) { if(data){ copiedObject =data; } else{ } }); return copiedObject; } 

As you can see the data contains the json results (data is all fine) but when i want to return the results it returns empty object.... how do i return the data from this ajax request so that the other function will use it? 你可以看到数据包含json结果(数据都很好)但是当我想返回结果时它返回空对象....我如何从这个ajax请求返回数据,以便其他函数将使用它? Obviously I cannot simply clone copiedObject =data; 显然我不能简单地克隆copiedObject = data;

The post call is asynchronous, so you have to use the value from the done function. 后调用是异步的,因此您必须使用done函数中的值。 Generally, you would do something like: 通常,你会做类似的事情:

function getAuctionItems()
{  
        var copiedObject = {};
        var jqxhr = $.post( "php/server.php", {command:'auctions'},function() {})
          .done(function(data) {

                if(data){
                    dosomethingWithData(data);
                }
                else{
                }
           });
}

function dosomethingWithData(data) {
  doSomethingwithThedata.......
} 

Because JavaScript isn't waiting around for an expensive process like a post, it has moved on, and is waiting for the done event to actually parse the data. 因为JavaScript没有等待像帖子这样昂贵的进程,所以它已经继续前进,并且正在等待done事件实际解析数据。

I am giving you an example how to do it- 我正在举例说明如何做到 -

$.ajax
    (
        {
            url:"ajax_state_load/"+$('#country_data').val(),success:function(result)
            {
                $("#car_model").html(result);
                $('#region_data')
                    .empty()
                    .append(result);
                ;
            }
            ,error:function()
            { 
                console.error('Region Load Failed.');
            }
        }
    );

And everything should be inside 一切都应该在里面

$(document).ready(function()

If you are using jQuery. 如果你正在使用jQuery。

This is because "copiedObject" is returned before the post request is completed. 这是因为在post请求完成之前返回“copiedObject”。

You might need something like... 你可能需要......

if(data)
{
  myOtherFunction(data);
}

Where "myOtherFunction" is a function you create to handle the returned data. 其中“myOtherFunction”是您创建的用于处理返回数据的函数。 Drew 德鲁

The typical way of handling this is by passing a callback to your function: 处理此问题的典型方法是将回调传递给您的函数:

function getAuctionItems(callback)
{  
    $.post( "php/server.php", {command:'auctions'},function() {})
        .done(function(data) {
            if (data) {
                callback(data);
            }
        });
}

Then, call like this: 然后,这样打电话:

getAuctionItems(function(data) {
    // do something with data
});

Ajax calls are async in nature. Ajax调用本质上是异步的。 Javascript won't wait for the response before returning copiedObject. 在返回copiedObject之前,Javascript不会等待响应。

Using callback is working fine, but a more elegant way is using Deferred and Promise. 使用回调工作正常,但更优雅的方式是使用Deferred和Promise。 It has more flexibility and decouple your ajax calls to your business logic. 它具有更大的灵活性,可以将ajax调用与业务逻辑分离。

To convert your code into Deferred/Promise way. 将代码转换为延迟/承诺方式。

function getAuctionItems()
{         
    return $.post( "php/server.php", {command:'auctions'});
}

Then in other method, call like this: 然后在其他方法中,调用如下:

getAuctionItems().done(function(data){
     //your logic to process data
});

Moreover, if you want to cache your data locally and make the data-fetching logic completely decoupled from your data-processing logic. 此外,如果要在本地缓存数据并使数据获取逻辑与数据处理逻辑完全分离。

var dataCached = null;

function fetchData(user){
    var dfd = $.Deferred();
    if(dataCached != null){
        dfd.resolve(dataCached);
    }else{
         $.post("three.htm", {
              user: user
          },function(data){
               dataCached = data;
              dfd.resolve(data);
         }); 
    } 

    return dfd.promise();
}

$.when(fetchData("Jack")).then(function(data){
   //play with the data
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM