如何从ajax返回值

Jav*_*vaH 0 ajax jquery

我已经使用jquery ajax从服务器获取值.当方法进入ajax成功或错误时,我需要返回值.如何做到这一点.请指导我.

$.ajax({
    cache: false,
    async: true,
    type: "GET",
    timeout:6000,
    dataType: "json",
    url:url +"log",
    data: { ContactEmail : $("#username").val()},
    contentType: "application/json;charset=utf-8",
    success: function (result) 
    {
        //Here I need to return the result and should get in another method
    },
    Error: function (e)
    {
        //Here I need to return the result and should get in another method
    }
});
Run Code Online (Sandbox Code Playgroud)

更新

例如, 当我调用checkNetConnection()时,它返回 value.i需要这样

function checkNetConnection() 
{
        var netresult=0;
        var networkState = navigator.network.connection.type;
        var states = {};
        states[Connection.UNKNOWN]  = 'Unknown connection';
        states[Connection.ETHERNET] = 'Ethernet connection';
        states[Connection.WIFI]     = 'WiFi connection';
        states[Connection.CELL_2G]  = 'Cell 2G connection';
        states[Connection.CELL_3G]  = 'Cell 3G connection';
        states[Connection.CELL_4G]  = 'Cell 4G connection';
        states[Connection.NONE]     = 'No network connection';
        if(states[networkState]=='Ethernet connection'||states[networkState]=='WiFi connection' || states[networkState]=='Cell 2G connection' || states[networkState]=='Cell 3G connection' || states[networkState]=='Cell 4G connection')
        {
            netresult=1;
        }
        else
        {
            netresult=0;
        }
        return netresult;
}
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 5

您的代码存在一些问题.您已指定contentType: "application/json;charset=utf-8"但未发送JSON请求.如果要发送JSON请求,请使用JSON.stringify数据上的方法:

data: JSON.stringify({ ContactEmail : $("#username").val() }),
Run Code Online (Sandbox Code Playgroud)

如果没有,请删除此contentType,否则服务器不明确.您的代码的另一个问题是调用错误回调error,而不是Error.就获取结果而言,在成功回调中,它们将直接作为参数传递:

success: function (result) {
    // Here I need to return the result and should get in another method
    anotherMethod(result);
},
Run Code Online (Sandbox Code Playgroud)

还应注意,如果Web服务器设置了正确的内容类型响应头,则传递给success方法的参数将自动由jQuery解析为基础类型.因此,例如,如果您的服务器设置Content-Type: application/json并写入{"foo":"bar"}响应主体,您可以直接操作此对象:alert(result.foo);在此回调内部,无需额外解析.如果您的Web服务器脚本写得不好并且没有设置正确的内容类型标头,例如它设置Content-Type: 'text/html'并将JSON格式的字符串写入响应主体,则可以使用该dataType: 'json'参数强制jQuery解析为JSON .但通常情况下,如果一切正确,你不应该这样做.

现在,error回调是不同的.它xhr作为参数传递给对象,因此您必须在此次将结果提取为字符串:

error: function(xhr) {
    anotherMethod(xhr.getResponseText());    
}
Run Code Online (Sandbox Code Playgroud)

如果此字符串表示JSON,您可以解析它:

error: function(xhr) {
    var result = $.parseJSON(xhr.getResponseText());
    anotherMethod(result);    
}
Run Code Online (Sandbox Code Playgroud)