相关疑难解决方法(0)

jQuery从php json_encode解析/显示json数据

jquery中的初始.ajax调用:

$.ajax({                                      
 type: 'post',
 url: 'items_data.php',                  
 data: "id="+id,                                       
 dataType: 'json',                     
 success: function(data){     
  if(data){
   make_item_rows(data);
  }else{
   alert("oops nothing happened :(");
  }        
 } 
});     
Run Code Online (Sandbox Code Playgroud)

将简单的字符串发送到php文件,如下所示:

header('Content-type: application/json');
require_once('db.php');

if( isset($_POST['id'])){
 $id = $_POST['id'];
}else{
 echo "Danger Will Robinson Danger!";
}

$items_data = $pdo_db->query ("SELECT blah blah blah with $id...");
$result_array = $items_data->fetchAll();
echo json_encode($result_array);
Run Code Online (Sandbox Code Playgroud)

我正好抓住$ result_array并将其传递给另一个函数.我仔细检查确实返回了正确的值,因为我可以将结果回显到我的页面,它显示如下内容:

[{"item_id":"230","0":"230","other_id":"700"},{"item_id":"231","0":"231","other_id":"701"},{"item_id":"232","0":"232","other_id":"702"}]
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚如何迭代结果,所以我可以将值注入我的HTML中的表中.这是我的功能:

function make_item_rows(result_array){  
 var string_buffer = "";
 $.each(jQuery.parseJSON(result_array), function(index, value){
  string_buffer += value.item_id; //adding many more eventually
  $(string_buffer).appendTo('#items_container');
  string_buffer = ""; //reset buffer after writing …
Run Code Online (Sandbox Code Playgroud)

php ajax jquery json

4
推荐指数
1
解决办法
5万
查看次数

标签 统计

ajax ×1

jquery ×1

json ×1

php ×1