使用jQuery和Ajax获取JSON数据

时间:2015-02-07 11:33:07

标签: jquery ajax

我正在尝试使用ajax填充div。这是代码

$.ajax({
    url: "/assets/location.php",
    //dataType:"json",
    success: function (result) {
        alert("hello");

        $.each(result, function (i, val) {
            alert("hello");
            alert(val.title);
        });
    }
});

服务器

<?php
require_once 'include.php';

$db = connect_db();
$query = 'CALL get_location()';
$result = mysql_query($query, $db) or die(mysql_error($db));
$data = array();
while ($row = mysql_fetch_array($result)) {
    array_push($data, $row);
}

echo(json_encode($data));
?>

一切正常,但当我取消注释dataType:&#34; json&#34;脚本停止执行成功功能。 请指出错误。

2 个答案:

答案 0 :(得分:1)

您的成功函数包含表达式JSON.parse(result)

dataType:"json"取消注释的情况下,jQuery会自动对数据进行json解码。

因此,JSON.parse(result)会尝试解码已解码的内容。

我猜你得到一个解析错误。检查你的控制台。

答案 1 :(得分:0)

没有dataType:'json'选项,您的代码应为。

$.ajax({
    url: "/assets/location.php",
    success: function (result) {
        alert("hello");

        //data is not parsed, so you have to explicitly parse to json
        $.each(JSON.parse(result), function (i, val) {
            alert("hello");
            alert(val.title);
        });
    }
});

使用dataType:'json'选项,您的代码应为。

  $.ajax({
        url: "/assets/location.php",
        dataType:'json',
        success: function (result) {
            alert("hello");

            //result is already parsed to json (by dataType option), 
            //So no need to parse again.
            $.each(result, function (i, val) {
                alert("hello");
                alert(val.title);
            });
        }
    });