This question already has answers here:
How do I return the response from an asynchronous call?
                                
                                    (36个答案)
                                
                        
                                去年关闭。
            
                    
我无法在ajax调用之外的控制台上打印已解析的json文件?我究竟做错了什么?

function displayData(term) {
   var frmStr =$('#input1').serialize();
   var result;

   $.ajax({
        url:'./cgi_temp4_1.cgi',
        dataType:'json',
        data: frmStr,
        success: function(data, textStatus, jqXHR){
            //alert(data)
            result = $.parseJSON(JSON.stringify(data))
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert("Failed to perform search! textStatus: (" + textStatus +
                  ") and errorThrown: (" + errorThrown + ")");
        }
    });

    //i get "undefined" message on the console
    console.log(result);


}

最佳答案

您正在发送异步请求,但尝试在结果准备好之前读取结果。

将console.log(result)移至第12行,作为成功回调的最后一行。

08-04 13:04