ajax成功时使用JSON结果

时间:2015-05-25 13:55:16

标签: javascript php jquery ajax json

我有这段代码:

function openIzmeni(value) {
$.ajax({
            url: "getRzaizmenu.php",
            type: "POST",
            async: true, 
            data: { vrednostid:value}, //your form data to post goes here as a json object
            dataType: "html",
            success: function(data) {  
            console.log(data);
            $('#brojracuna1').val(data[0].br);
            console.log(data[0].br);
            console.log(data.br);

所以你可以看到我调用getRzaizmenu.php来获取JSON输出。 getRzaizmenu.php代码是:

try {


     $result = $db->prepare("SELECT * FROM racuni WHERE ID=:id AND user_id=:user_id");
     $result->execute(array(':id' => $_POST['vrednostid'], ':user_id' => $user_id));
    $result = $result->fetchAll(); 

     $r= json_encode($result);
    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }
     echo $r;

这个php给我输出输出:

[{"ID":"22","0":"22","prefiks":"","1":"","br":"14321","2":"14321","sufiks":"993.67","3":"993.67","kupac":"Pavle Aleksov","4":"Pavle Aleksov","adresa":"Desanka Maksimovic 6\/a","5":"Desanka Maksimovic 6\/a","grad":"18320 Dimitrovgrad","6":"18320 Dimitrovgrad","pib":"567890","7":"567890","total":"1200.00","8":"1200.00","valuta":"Din","9":"Din","nacin":"gotovinsko","10":"gotovinsko","datum":"2015-05-25","11":"2015-05-25","rok":"2015-05-25","12":"2015-05-25","isporuka":"2015-05-25","13":"2015-05-25","naplaceno":"0000-00-00","14":"0000-00-00","napomene":"","15":"","interne":"","16":"","jezik":"","17":"","status":"","18":"","sifra":"yyx5y","19":"yyx5y","user_id":"1","20":"1"}]

因此,此代码返回给我"0":22"ID":22,但它是同一列。

你可以看到我尝试将这些数据用于这样的ajax成功函数:

success: function(data) {  
                console.log(data);
                $('#brojracuna1').val(data[0].br);
                console.log(data[0].br);
                console.log(data.br);

但我未定义。

如何才能成功使用data

3 个答案:

答案 0 :(得分:2)

更改

dataType: "html",

dataType: "json",

再试一次。

答案 1 :(得分:1)

您已编码数据,这没关系。 但解析时你并没有解码数据。所以你必须使用JSON.parse()和解析函数来解码数据。

答案 2 :(得分:0)

你需要解析JSON,试试这个

success: function(data) {  
    $.each(data, function(index, element) {
        console.log(index);
        console.log(element);
    });
});