简体   繁体   English

使用Ajax成功处理程序返回JSON对象

[英]Use Ajax Success Handler to return JSON object

I am using an Ajax command to query data from a local server and I need to return a JSON object via the success handler. 我正在使用Ajax命令从本地服务器查询数据,并且需要通过成功处理程序返回JSON对象。

My Ajax command looks like this: 我的Ajax命令如下所示:

var json = $.ajax({
    url: 'http://localhost:9200/wcs/routes/_search',
    type: 'POST',
    data: JSON.stringify({
        "query": {
            "match_all": {}
        }
    }),
    dataType: 'json',
    async: false
});

I'd like to return the JSON document in the variable that I already have assigned: json 我想在已经分配的变量中返回JSON文档: json

Could I do something like this in the command? 我可以在命令中这样做吗? (I know this isn't correct code): (我知道这不是正确的代码):

success: return(json);
});

You were close, 你很亲密

var json;
$.ajax({
    url: 'http://localhost:9200/wcs/routes/_search',
    type: 'POST',
    data :
        JSON.stringify(
            {
                "query" : { "match_all" : {} }
        }),
    dataType : 'json',
    async: false,
    success: function(data){
        json = data;
    }
})
console.log(json);

but async: false is a bad idea, so i'd suggest using json inside the callback. async: false是个坏主意,因此我建议在回调内使用json。

$.ajax({
    url: 'http://localhost:9200/wcs/routes/_search',
    type: 'POST',
    data :
        JSON.stringify(
            {
                "query" : { "match_all" : {} }
        }),
    dataType : 'json',
    //async: false,
    success: function(data){
        console.log(data);
    }
})

Success expect's A function to be called if the request succeeds. 如果请求成功,将调用Success期望的A函数。

You can do this : 你可以这样做 :

var json:
....
....

success: function(data){
       json = data;
   }
});
 var arr = new Array();
 success: function (data) {
    $.map(data, function (item) {
          arr.push({
              prop_1: item.prop_1,
              prop_2: item.prop_2,
              prop_3: item.prop_3
             });
           });
      }

You can rename prop_1, prop_2 vs up to your codebehind 您可以重命名prop_1,prop_2与您背后的代码

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

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