[英]Get Element value from Ajax response
我是Jquery和Ajax调用的新手...这是我的调用:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "some url",
success: function(response){
console.log(response);
}
})
});
控制台日志显示以下响应:
{"2014/08/08":[{},{"TEST":0}]}
如何将TEST
的值保存到变量?
类似于var t = document.getElementById('test').value
使用JSON.parse
$(document).ready(function () {
$.ajax({
type: "GET",
url: "some url",
success: function(response){
try{
json = JSON.parse(response);
test = null;
$.each(json,function(i,item){
test = item[1].TEST;
});
alert(test);//this is what you want
}catch(e){}
}
})
});
服务器的响应是json,因此处理它的最好方法是告诉jQuery
期待一个json答案并将其转换为常规javascript对象。 这是通过在$.ajax(...)
调用中添加dataType: 'json'
来完成的:
$.ajax({ type: "GET", url: "some url", dataType: "json", success: function(response){ console.log(response); } })
您也可以使用快捷方式$.getJSON(...)
:
$.getJSON("some url", function(response){ console.log(response); });
现在您有了一个常规的javascript对象,您可以使用其他答案提示:
success: function(response) { console.log(response["2014/08/08"][1].TEST); // or $.each(response, function(i, itm) { console.log(itm[1].TEST); }; }
尝试这个,
$.each(response,function(i,value){
alert(value[1].Test);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.