使用 AJAX 检索 JSON 数据


Retrieve JSON Data with AJAX

我试图从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");
          }
}); 

当这在浏览器中运行时,只是说"邮政编码:未定义"。

这是从数据库中选择数据的 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

您缺少数据类型:

$.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"); });

看看你的代码在做什么。

首先,将数据直接放入#txtHint框中。

然后,对于每个数据元素,创建字符串"Postcode: "+value.postcode(甚至不检查value.postcode是否存在 - 它可能不存在)并用它覆盖#txtHint的 html。

最终结果:脚本正在执行您告诉它执行的操作。

删除那个循环的东西,看看你得到了什么。

JSON 数据是否表示包含相同对象结构的多行?请在成功函数中提醒数据对象并发布它,以便我们帮助您调试它。

使用

dataType: 'json'

ajax 调用中的参数或使用 $.getJSON() 它会自动将 JSON 数据转换为 JS 对象。

您也可以在成功回调中使用 $.parseJSON() 自己将 JSON 响应转换为 JS 对象,如下所示

data = $.parseJSON(data);

这在您的网站上对我有用:

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);
        }
    });
}