如何使用jQuery.parseJSON获取数据

How get data with jQuery.parseJSON

本文关键字:获取 数据 parseJSON jQuery 何使用      更新时间:2023-09-26

在第1页中,我有一个数组:

$pole = array("countLike" => "countLike", "Message" => "Some message");
echo json_encode($pole);

我想在第2页上得到这些数据,但这些代码不起作用。

function Like(id)
{
    $.post("page1.php", { action: "Like", "id": id }, function(data) {
        var obj = jQuery.parseJSON(data);
        $(".countLike#"+id).html(obj.countLike);
        $(".Message#"+id).html(obj.Message);
    });
} 

你能帮我查一下这个密码吗。谢谢

根据post请求的预期输出传递json

function Like(id)
{
    $.post("page1.php", { action: "Like", "id": id }, function(data) {
        //data is already a json parsed string
        $(".countLike#"+id).html(data.countLike);
        $(".Message#"+id).html(data.Message);
    }, "json"); // <<<<< This is what you missed
} 

代码应该可以处理请求,但元素选择器有问题。

".countLike#"+id 
".Message#"+id

"#"与类名之间没有空格分隔。现在的问题变成了你在寻找ID为"#"+ID的元素吗?我怀疑你是这样的,所以你真的不需要类在ID前面加前缀,只需使用

$('#' + id)

对于jQuery来说,Id选择器的搜索速度要比类快得多,因为页面中只能有一个。