我正在开发一个spring hibernate项目。我试图以Json对象的形式获取数据,并根据该Json数据填充下拉列表。我正在使用ajax jquery调用,但作为回报我只得到[对象对象] [对象对象] ...我在google开发者控制台中调试jquery并且我收到错误(json对象包含两个字段brandID和BrandName)
Uncaught SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at Object.success (AddItem:51)
at i (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at A (jquery.min.js:4)
at XMLHttpRequest.<anonymous> (jquery.min.js:4)
success @ AddItem:51
i @ jquery.min.js:2
fireWith @ jquery.min.js:2
A @ jquery.min.js:4
(anonymous) @ jquery.min.js:4
这是jquery代码
<script type="text/javascript">
$(document).ready(function(){
$('#ItemCategory').change(function(){
$.ajax({
type : 'post',
url : "${home}/Admin/AddItem",
data : {dropdown: $('#ItemCategory').find(":selected").val()},
datatype : 'html',
success : function(responseText)
{
$('#BrandList').empty().append($('<option>').val('-1').text('select brand..'));
$.each(JSON.parse(responseText),function(index,element){
$('#BrandList').append($('<option>',{value:element.BrandID,text:element.BrandName}));
});
$('#BrandList').selectpicker('refresh');
}
});
});
});
</script>
servlet代码
public String getbrand(String catid){
List<BrandLoader> list = brand_Service.getItemBrand(catid);
json = null;
json = gson.toJson(list);
System.out.println(list);
System.out.println(json);/* output see below */
return json;
}
我得到了正确的json但仍然是同样的问题
[{"BrandID":"brand-21","BrandName":"HTC"},{"BrandID":"brand-22","BrandName":"Sony"},{"BrandID":"brand-23","BrandName":"Lenovo"},{"BrandID":"brand-24","BrandName":"Micromax"},{"BrandID":"brand-25","BrandName":"Panasonic"},{"BrandID":"brand-26","BrandName":"Vivo"}]
实体类
@Entity
@Table(name="brand")
public class BrandLoader {
@Id
private String BrandID;
@Column(name="brandname")
private String BrandName;
@Column(name="cat_id")
private transient String Cat_ID;
@Override
public String toString() {
return "id :"+BrandID+" brand_name :"+BrandName;
}
public String getBrandID() {
return BrandID;
}
public void setBrandID(String brandID) {
BrandID = brandID;
}
public String getBrandName() {
return BrandName;
}
public void setBrandName(String brandName) {
BrandName = brandName;
}
public String getCat_ID() {
return Cat_ID;
}
public void setCat_ID(String cat_ID) {
Cat_ID = cat_ID;
}
}