2017-05-08 34 views
-1

我发现一个奇怪的问题。AJAX响应,不能提醒JSON字符串正确

使用php我正在运行mysql数据库的select查询,我试图将此返回给我的ajax调用,所以我可以通过它循环,但我总是得到未定义的警报,我可以警告整个json字符串但是,但不能达到目标值。

Ajax代码:

 $.ajax({ 
      type: "POST", 
      url: 'database_data.php', 
      data: { 
       action: 'ct', 
       input: input 
      }, 
      success: function (data) { 
       var obj = JSON.parse(data); 
       alert(obj[0].pid); 
       alert(data[0].pid); 
      },error: function(request, status, error){ 
       alert("Error: Could not delete"); 
      } 
     }); 

PHP代码:

$base= mysqli_connect($dbhost, $dbuser, $dbpass, $dbbase); 
if ($_POST['action']== "ct"){ 
    $input = $_POST['input']; 
    $return_arr = array(); 
    $sql = "SELECT pid FROM programmes WHERE complete_title LIKE '%$input%' LIMIT 30"; 

if ($result = mysqli_query($base, $sql)){ 
    while ($row = mysqli_fetch_assoc($result)) { 
     $row_array['pid'] = $row['pid']; 
     array_push($return_arr,$row_array); 
    } 
} 

mysqli_close($base); 

echo json_encode($return_arr); 

}

警报数据给出的这样的回应:

[{"pid":"p00547jm"},{"pid":"p0054880"},{"pid":"p005492h"},... 

如果我选择了报警数据[0],它打印每个数据[1]个性字符

+0

'$阿贾克斯({ 数据类型: “JSON”, 网址:网址, 数据:数据, 成功:成功 });'添加数据类型或使用简写:http://api.jquery.com/jquery.getjson/ – ippi

+0

您正在提醒未分析的数据[0]。 – rishipuri

+0

'obj'是一个数组,因此您需要使用适当的索引:'obj [0] .pid' – CBroe

回答

0

您可以使用dataType告诉jQuery的你从服务器期待回。见http://api.jquery.com/jquery.ajax/

在你的情况

$.ajax({ 
      type: "POST", 
      url: 'database_data.php', 
      dataType: 'json', 
      data: { 
       action: 'ct', 
       input: input 
      }, 
      success: function (data) { 
       var obj = data; // I should already be json! 
       alert(obj.pid); 
       alert(data.pid); 
      },error: function(request, status, error){ 
       alert("Error: Could not delete"); 
      } 
     }); 
0

这是因为您可能获取字符串作为响应。所以你的datastring

您可以使用JSON.parse()将它解析为JSON对象和访问这样的数据,

data = '[{"pid":"p00547jm"},{"pid":"p0054880"},{"pid":"p005492h"}]'; 
 

 
console.log(JSON.parse(data)[0].pid);

+0

他已经完成了JSON.parse()。请参阅html代码 – bigbounty

+0

@bigbounty他仍然需要首先访问正确的数组元素。 – CBroe