我试图从JSON对象中检索一些数据,这些数据包含街道名称,邮政编码等位置信息。但是当我尝试将其放入我的div时,没有任何内容被检索到。任何人都可以看到我的错误吗?
这是我的ajax代码,用于请求和检索数据
var criterion = document.getElementById("address").value;
$.ajax({
url: 'process.php',
type: 'GET',
data: 'address='+ criterion,
success: function(data)
{
$('#txtHint').html(data);
$.each(data, function(i,value)
{
var str = "Postcode: ";
str += value.postcode;
$('#txtHint').html(str);
});
//alert("Postcode: " + data.postcode);
},
error: function(e)
{
//called when there is an error
console.log(e.message);
alert("error");
}
});
当在broswer中运行时,只是说“Postcode:undefined”。
这是从数据库中选择数据的php代码。
$sql="SELECT * FROM carparktest WHERE postcode LIKE '".$search."%'";
$result = mysql_query($sql);
while($r = mysql_fetch_assoc($result)) $rows[] = $r;
echo json_encode($rows), "\n"; //Puts each row onto a new line in the json data
答案 0 :(得分:2)
您缺少数据类型:
$.ajax({
dataType: 'json'
})
您也可以使用$.getJSON
编辑:JSON的示例
$.getJSON('process.php', { address: criterion } function(data) {
//do what you need with the data
alert(data);
}).error(function() { alert("error"); });
答案 1 :(得分:1)
看看你的代码在做什么。
首先,将数据直接放入#txtHint
框。
然后,对于每个数据元素,创建字符串"Postcode: "+value.postcode
(甚至不检查value.postcode
是否存在 - 它可能不存在)并用它覆盖#txtHint
中的html。< / p>
最终结果:脚本完全按照您的要求执行操作。
删除那个循环的东西,看看你得到了什么。
答案 2 :(得分:0)
您的JSON数据是否代表包含相同对象结构的多行?请提醒您成功函数中的数据对象并发布,以便我们帮助您进行调试。
答案 3 :(得分:0)
使用
dataType: 'json'
你的ajax电话中的param 或者使用$.getJSON()这将自动将JSON数据转换为JS对象。
您也可以使用$.parseJSON()内部成功回调将JSON响应转换为JS对象
data = $.parseJSON(data);
答案 4 :(得分:0)
这适用于您的网站:
function showCarPark(){
var criterion = $('#address').val();
// Assuming this does something, it's yours ;)
codeAddress(criterion);
$.ajax({
url: 'process.php',
type: 'GET',
dataType: 'json',
data: {
address: criterion
},
success: function(data)
{
$("#txtHint").html("");
$.each(data, function(k,v)
{
$("#txtHint").append("Postcode: " + v.postcode + "<br/>");
});
},
error: function(e)
{
alert(e.message);
}
});
}