SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
我在使用$.parseJSON解析后台返回的JSON的數據時,出現了這樣的錯誤,我還以為返回的JSON格式出現了錯誤,因為JSON要求格式非常嚴格。最后發現JSON格式沒有太明顯的格式錯誤,我使用fastJSON來生成的JSON格式數據,原來是因為數據已經是一個JavaScript對象了,所以在進行解析就會出錯了
我直接將這段數據alert出來,並使用typeof檢驗其類型,發現是一個Object,這就證明了數據已成為了JavaScript對象了。所以,我直接使用(不用什么parseJSON解析了)這段數據進行相應的處理就不會出錯
$.ajax({ url : 'commentAction_showComment', type : 'POST', data:{ titleid: $(comment_this).attr('data-id'), currPage : currPage, }, beforeSend : function (jqXHR, settings) { $('.comment_list').eq(index).append('<dl class="comment_load"><dd>正在加載評論</dd></dl>'); }, success : function (response, status) { var json_comment = response; }, });
也許是我對jQuery的parseJSON方法理解錯誤使用不當,或者是該用其他的方法處理?
后台響應的是JSON格式的字符串而不是JSON對象
如果后台發送的是一個JSON格式的字符串(注意:是字符串,只是采用JSON的語法格式,不是JSON數據),我們在前台應該怎樣解析成一個JSON對象呢?
后台代碼:
PrintWriter out = response.getWriter(); String username = request.getParameter("user"); String password = request.getParameter("pwd"); String data = "{'username':'"+username+"','password':'"+password+"'}"; System.out.println(data); out.write(data);
這個data就是一個JSON格式的字符串
我們需要將eval()方法將這個字符串包一下,就可以轉成JSON對象了,eval應該是一個JavaScript中的方法:
$.ajax({ //一個Ajax過程
type : "post", //以post方式與后台溝通
url : "Ajax_jQueryServlet", //與此php頁面溝通
data : 'username=' + username + '&password=' + password,
success : function(data) {
var json = eval('(' + data + ')');
$('#result').html(
"姓名:" + json.username + "<br/>密碼:" + json.password);
}
});
注:eval('('+text+')')將JSON格式的字符串text解析為成具體的類型,如boolean什么的,有時可能需要使用eval('['+text+']') 方括號來包裹JSON字符串,可以解析為數組,也就是Object類型。具體使用看情況吧
