我想从ajax的success中获得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,上面的选择是循环迭代的,所以我必须使用每个循环来知道我正在使用的是哪个下拉列表(只是为了通知用户)。
$('.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);函数,我的代码有什么问题吗?还是我误用了代码?
The success callback function seems to be failing to parse the JSON result.
Try passing a value to your servlet as a URL query string like http://localhost/project/Analysis?team=some-value-you-know
Then validate the printed JSON using a tool like http://jsonlint.com", fix the JSON you're generating [probably double quotations around the JSON object keys].
Also try using the Developer Tools's JavaScript console in your browser, it will help you with the JavaScript errors.
Hope this helps,
Shareb.
Silly me, alright i found the answer change the code from the 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 );
}
}
to
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;
}
I just added return;