0

我正在尝试在 jquery 对话框中显示一些 mysql 数据,当我使用这段代码时,这工作得很好:

询问:

 $con = mysql_connect($host,$user,$pass);
  $dbs = mysql_select_db($databaseName, $con);

  //--------------------------------------------------------------------------
  // 2) Query database for data
  //--------------------------------------------------------------------------
  $result = mysql_query("SELECT * FROM $tableName");          //query
  $array = mysql_fetch_row($result);                          //fetch result    

  //--------------------------------------------------------------------------
  // 3) echo result as json 
  //--------------------------------------------------------------------------
  echo json_encode($array);

输出:

 $(function () 
  {
    //-----------------------------------------------------------------------
    // 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
    //-----------------------------------------------------------------------
    $.ajax({                                      
      url: 'api.php',                  //the script to call to get data          
      data: "",                        //you can insert url argumnets here to pass to api.php
                                       //for example "id=5&parent=6"
      dataType: 'json',                //data format      
      success: function(data)          //on recieve of reply
      {
        var URL = data[3];              //get id
        var approved = data[4];           //get name

        //--------------------------------------------------------------------
        // 3) Update html content
        //--------------------------------------------------------------------
        $('#output').html("<b>URL: </b>"+URL+"<b>  Status: </b>"+approved); //Set output element html
        //recommend reading up on jquery selectors they are awesome 
        // http://api.jquery.com/category/selectors/
      } 
    });
  }); 

使用它时,我得到了这个结果:

["1","peter","test.com","yes"]

这行得通,但是我要显示的条目不止 1 个,所以我这样做:

      $result = mysql_query("SELECT * FROM $tableName WHERE username='$username'");            //query
  while($array = mysql_fetch_array($result))
  {echo json_encode($array);
  } 

这给了我以下结果:

    {"0":"1","id":"1","1":"peter","username":"peter","2":"test.com","URL":"test.com","3":"yes","approved":"yes"}
{"0":"2","id":"2","1":"peter","username":"peter","2":"tessst.com","URL":"tessst.com","3":"yes","approved":"yes"}

这是为什么 ?它是否还获取行名(看起来像那样)?

我需要做什么才能使这项工作/以相同的格式获取它以便输出工作?

4

1 回答 1

0

mysql_fetch_array($result) 的结果(而不是 mysql_fetch_row($result))具有可通过键和索引访问的数据(data["id"]=data[0]、data["name"]=data[1] 等...)。

您还可以通过回显几个既没有分隔符也没有附件的有效字符串({...}{...}{...} 而不是 [{...},{...} ,{...}])

于 2012-12-28T12:06:52.023 回答