gpt4 book ai didi

php - jQuery 解析/显示来自 php json_encode 的 json 数据

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:59:23 24 4
gpt4 key购买 nike

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 :(");
}
}
});

将一个简单的字符串发送到一个 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);

我很好地捕获了 $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"}]

我无法弄清楚如何遍历结果,以便将值注入(inject)到 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
});
}

我还尝试在 $.each 函数中放置一个警报,以确保它触发了 3 次,确实如此。但是我的代码中没有数据。也尝试过其他一些方法,但没有成功。

更新:我更改了我的代码以包含 parseJSON,没有骰子。在我的 jquery 文件中出现意外的标记错误(就在它尝试使用 native json 解析器时)。尝试添加 json header 无济于事,同样的错误。 jquery 版本 1.9.1。现在的代码应该反射(reflect)在上面。

最佳答案

在您的 ajax 调用中设置 dataType:"JSON" 和回调。

例如:

$.ajax({
url: "yourphp.php?id="+yourid,
dataType: "JSON",
success: function(json){
//here inside json variable you've the json returned by your PHP
for(var i=0;i<json.length;i++){
$('#items_container').append(json[i].item_id)
}
}
})

请同时考虑在您的 PHP 中设置 JSON 内容类型。 header('Content-type: application/json');

关于php - jQuery 解析/显示来自 php json_encode 的 json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15733972/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com