我的 php json 中有这种形式的数据:
string(170) "[{"id":"3","Name":"Kontrahent#322","NIP":"753","Adress":"Wiosenna29","PostCode":"20-201","City":"Olkusz","Phone":"12312312","Email":"jakub@edu.pl","Value":"0"}]"
和我的功能:
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var val = $('#test').val()
var id = $('#clientsname option').filter(function() {
return this.value == val;
}).data('id');
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
var data = xmlhttp.responseText;
alert(data[0].Name);
}
}
xmlhttp.open("GET","getclients/"+id);
xmlhttp.send();
}
}
警报(数据[0].名称);或警报(数据。名称);返回未定义。 控制台日志(数据); 返回:
string(141) "[{"id":"1","Name":"Kontrahent #1","NIP":"735256985","Adress":"","PostCode":"","City":"","Phone":"777555888","Email":"e@mail.pl","Value":"0"}]"
我不知道我的脚本有什么问题。任何人都可以帮助我吗?
最佳答案
您需要使用 JSON.parse
将响应解析为 JSON方法,因为 xmlhttp.responseText
只是一个字符串:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
var data = JSON.parse(xmlhttp.responseText);
alert(data[0].Name);
}
}
关于javascript - 返回未定义的 jQuery JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30413512/