2

我是codeigniter框架和json的新手。当用户单击 url 时,我想从数据库中获取数据,但出现错误。

我的脚本:

function abc(i)
{
   if(i == 1)
   {
     $.ajax({
       type: "post",
       url: "<?php echo base_url('welcome/liststd');?>",
       data: 'postData='+ i ,
       success: function(json)
       {
         var abc = json;
         document.getElementById("fname").innerHTML=abc[0].fname; 
       }
    });
  }
 }

萤火虫回应:

[
   {
     "id":"31",
     "fname":"Darshan",
      "mname":"D",
      "lname":"Dave",
      "std":"1",
      "marks":"12000",
      "image":"image31.jpg",
      "id1":"1",
      "in_date":"0000-00-00",
      "upd_date":"2013-07-10"
   },
   {
      "id":"34",
      "fname":"Darshan",
      "mname":"D",
      "lname":"Dave",
      "std":"1",
      "marks":"12000",
      "image":"image34.jpg",
      "id1":"1",
      "in_date":"2013-07-06",
      "upd_date":"2013-07-09"
     }
   ]

json当我在success函数中发出警报时,它会向我显示:

[
   {
     "id":"31",
     "fname":"Darshan",
      "mname":"D",
      "lname":"Dave",
      "std":"1",
      "marks":"12000",
      "image":"image31.jpg",
      "id1":"1",
      "in_date":"0000-00-00",
      "upd_date":"2013-07-10"
   },

我的错误是什么?

4

2 回答 2

3

您没有解析 JSON。添加dataType : 'json'到 ajax 调用。这将告诉 jQuery 自动为您解析 JSON。

 $.ajax({
     type: "post",
     url: "<?php echo base_url('welcome/liststd');?>",
     data: 'postData=' + i,
     dataType: 'json', // <----- tell jQuery to parse the JSON
     success: function (json) {
         var abc = json;
         document.getElementById("fname").innerHTML = abc[0].fname;
     }
 });
于 2013-07-11T06:33:53.290 回答
0
try this in your response...
also in your $.ajax tell jquery to parse json
 dataType: 'json'
in your response..
var response = JSON.parse(json);
response.fname;
于 2013-07-11T06:42:58.343 回答