成功时,Ajax GET请求为null

时间:2013-06-19 17:14:03

标签: jquery ajax http get

我是JS的新手,在尝试通过ajax调用向我的服务器发送GET请求时遇到了一个问题。服务器正在接收请求并正在执行get,并且ajax调用确实成功(执行success函数),但响应为null。在Postman中测试时,GET可以正常工作。

Ajax Call:

url = "http://localhost:8080/EmployeeLookup/SearchServlet?search=test"
$.ajax({
    url: url,
    type: 'GET',
    success: display,
    error: function(xhr,status,error){ alert(status); },
}); 

请求被发送到提供此页面的同一服务器,因此Access-Control-Allow-Origin没有任何问题。

任何帮助将不胜感激。

提前致谢。

编辑:

显示功能:暂时测试它是否为null。使用===进行测试也会返回true。

function display(json) { 
    if(json == null) { 
        $("#text").replaceWith(json); 
    } else { 
        $("#text").replaceWith("Response was null. "); 
    }
}

发回的JSON类似于:

{
     "seachResult": "someresult" 
}

1 个答案:

答案 0 :(得分:2)

您应该始终指定dataType,以便jQuery能够一致地正确解析它。

// the http portion is not needed for same-domain requests
var url = "/EmployeeLookup/SearchServlet?search=test"
$.ajax({
    url: url,
    type: 'GET',
    dataType: 'json',
    success: display,
    error: function(xhr,status,error){ alert(status); },
}); 

function display(json) {
    console.log(json);
}

测试是否返回数据将不仅仅是测试它是否为null,如果你使用的是jQuery 1.9+和json dataType,它将永远不会为null。