简体   繁体   English

在Ajax成功函数中返回字符串

[英]Returning string in Ajax success function

I'm trying to return a string back after my Ajax is executed, however; 但是,我试图在执行Ajax之后返回一个字符串。 I'm getting the word undefined instead of the string. 我得到的单词是undefined而不是字符串。 I understand that the code is being executed asynchronously, but I don't understand how I can make a solution for my problem. 我知道代码是异步执行的,但是我不知道如何为我的问题提供解决方案。

JS JS

function aggregator(field){
    var query = '{"aggs": { "group_by_date": { "terms": { "field": "' + field + '" } } } }';

     $.ajax({
        url: 'index.php',
        type: 'post',
        data: {
            qSet: query
        },
        success: function(message){
            return message;
        }
    });

}

   var results = aggregator("transactionDate");
   document.getElementById("results").innerHTML = results;

How do I make it so that my element in HTML has the returned value? 如何使HTML中的元素具有返回值?

welcome to asynchronous programming. 欢迎使用异步编程。 You must either process your return value inside the callback of the ajax function, or use some kind of deferred queue based on promises for example. 您必须在ajax函数的回调中处理返回值,或者使用基于promise的某种延迟队列。

For a quick solution of your problem, try the first technique: 为了快速解决问题,请尝试第一种方法:

function aggregator(field,element){
    var query = '{"aggs": { "group_by_date": { "terms": { "field": "' + field + '" } } } }';

     $.ajax({
        url: 'index.php',
        type: 'post',
        data: {
            qSet: query
        },
        success: function(message){
            document.getElementById(element).innerHTML=message;
        }
    });

}

aggregator("transactionDate","results");

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

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