Ajax using Gson



我想从ajaxsuccess中获取json对象,这就是我到目前为止所做的

我的下拉列表

<select id="testers_team" class="tester_team">
    <optgroup label="Current Value">
        <option><c:out value="${info.team}"></c:out></option>
    </optgroup>
    <optgroup label="Teams">
        <c:forEach var="team" items="${requestScope.testers}">
            <option value="${team.key}">${team.key}</option>
        </c:forEach>
    </optgroup>
</select>

这是我的Ajax,上面的select由循环迭代,所以我必须使用每个来知道我正在使用哪个下拉列表(只是为了通知你们)

$('.tester_team').each(function(){
    $(this).change(function() {
          $.ajax({
         url: 'Analysis',
         type: 'POST',
         dataType: 'json',
         data: {team: $(this).val()},
         success: function(data){
             alert(data); // alert not working
         }
          });
    }); 
});

我在我的servlet上使用Gson代码:

String team = request.getParameter( "team" );
HashMap<String, ArrayList<String>> testerList
              = new UsersDAO().getTestersOfAllTeams();
ArrayList<String> testers = testerList.get( team );
if( testers != null )
{
    response.setContentType( "application/json" );
    response.setCharacterEncoding( "UTF-8" );
    try
    {
        response.getWriter().write( new Gson().toJson( testers ) );
        //this one is printing so that means it actually succeed to parse?
        System.out.println( team );
    }
    catch( IOException e )
    {
       // just want to test out if it really failed
       System.out.println( "failed" ); 
       log.debug( "Unable to get parse request", e );
    }
}

问题出在脚本中,当我更改下拉列表时,Ajax不会触发alert(data);函数,我的代码有什么问题? 还是我滥用了代码?

成功回调函数似乎无法解析 JSON 结果。

尝试将值作为 URL 查询字符串传递给 servlet,如 http://localhost/project/Analysis?team=some-value-you-know

然后使用 http://jsonlint.com 这样的工具验证打印的 JSON",修复您正在生成的 JSON[可能在 JSON 对象键两边加上双引号]。

还可以尝试在浏览器中使用开发人员工具的JavaScript控制台,它将帮助您解决JavaScript错误。

希望这有帮助,
沙雷布。

愚蠢的

我,好吧,我找到了答案,从servlet更改代码:

if( testers != null )
{
    response.setContentType( "application/json" );
    response.setCharacterEncoding( "UTF-8" );
    try
    {
        response.getWriter().write( new Gson().toJson( testers ) );
        //this one is printing so that means it actually succeed to parse?
        System.out.println( team );
    }
    catch( IOException e )
    {
       // just want to test out if it really failed
       System.out.println( "failed" ); 
       log.debug( "Unable to get parse request", e );
    }
}

if( testers != null )
{
    response.setContentType( "application/json" );
    response.setCharacterEncoding( "UTF-8" );
    try
    {
        response.getWriter().write( new Gson().toJson( testers ) );
        //this one is printing so that means it actually succeed to parse?
        System.out.println( team );
    }
    catch( IOException e )
    {
       // just want to test out if it really failed
       System.out.println( "failed" ); 
       log.debug( "Unable to get parse request", e );
    }
    return;
}

我刚刚添加了return;

最新更新