簡體   English   中英

無法使用jquery $ .ajax訪問從php頁面檢索的json數據

[英]Unable to access json data retrieved from php page using jquery $.ajax

如何在JavaScript中訪問此json數據。 當我提醒它結果undefined

這是jQuery代碼

$.ajax({
    type: "POST",
    url: "frmMktHelpGridd.php",
    data: {
        labNo: secondElement
    },
    dataType: "json",
    beforeSend: function () {
        // Do something before sending request to server
    },
    error: function (jqXHR, textStatus, errorThrown) {
        alert('error has occured');
        alert(errorThrown);
    },
    success: function (data) {

        //Here is the problem

        alert(data[0]['Result']);
    }
});

這是PHP代碼

            $data=array($no);
    for($i=0;($i<$no && ($row=mysql_fetch_array($result)));$i++)
    {
        $data[$i]=array();
        $data[$i]['Result']         =   $row['Result'];         
        $data[$i]['TestCode']       =   $row['TestCode'];           
        $data[$i]['TestStatus']     =   $row['TestStatus'];         
        $data[$i]['SrNo']           =   $row['SrNo'];               
    }

    $data1=json_encode($data);

    echo $data1;
      exit;

我已經獨立測試過PHP文件,json數據輸出如下:

      [{"Result":"1","TestCode":"22","TestStatus":"0","SrNo":"1"},{"Result":"1","TestCode":"23","TestStatus":"1","SrNo":"2"}]
$.ajax({
    type: "POST",
    url: "frmMktHelpGridd.php",
    data: {
        labNo: secondElement
    },
    dataType: "json",
    beforeSend: function () {
        // Do something before sending request to server
    },
    error: function (jqXHR, textStatus, errorThrown) {
        alert('error has occured');
        alert(errorThrown);
    },
    success: function (data) {
        //Added parse json
        var data = jQuery.parseJSON(data)

        alert(data[0]['Result']);
    }
});

您可以通過以下方式訪問數據

data[0].Result

它是一個對象,而不是數組。

所以data[0]['Result']這不是正確的方法

編輯 :由於您有更多的對象,您必須以這種方式執行循環:

$.each(data, function(key, val){
    console.log(val.Result);
    console.log(val.TestCode);  
    //...
});

當你看到類似的東西

{
    "foo":"bar",
    ...
}

您可以通過與上述相同的方式訪問它:

name_of_the_object.foo

值將為“ bar”

嘗試添加解析JSON。 我已經添加了。 現在可能會起作用。

$.ajax({
    type: "POST",
    url: "frmMktHelpGridd.php",
    data: {
        labNo: secondElement
    },
    dataType: "json",
    beforeSend: function () {
        // Do something before sending request to server
    },
    error: function (jqXHR, textStatus, errorThrown) {
        alert('error has occured');
        alert(errorThrown);
    },
    success: function (data) {
        //Added parse json
        var data = $.parseJSON(data)

        alert(data[0]['Result']);
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM