dpiw16824
dpiw16824
2019-08-06 16:00

如何使用AJAX从PHP获取JQuery数据[关闭]

已采纳

How to prepare JSON data

            $.post("../../pos/getArticles.php",
                {
                    userid: user
                },
                function(data, status){
                    var objData = JSON.parse(data);
                    for (i in objData){
                        objData[i][0] = "<td><a href='"+objData[i][2]+"'>"+objData[i][0]+"</a></td>";
                    }
                    addDataToArticles(objData);
                    // alert("Data: " + data + "
Status: " + status);
                });

I tried with return and echo and print_r keywords and functions to return JSON array but its not working

return array with echo!

echo $MyArticles = array (
 array("articleName1","count1","link1"),
 array("articleName2","count2","link2"),
 array("articleName3","count3","link3"),
 array("articleName4","count4","link4"),
 array("articleName5","count5","link5") 
);
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • duanjiong5686 duanjiong5686 2年前

    The best way is to use json_encode() when you return data from php to JS, here is example based on your code:

    JS:

    $( document ).ready(function() {
                    $.post("../../pos/getArticles.php",
                    {
                        userid: 1
                    },
                    function(data, status){
                        var objData = JSON.parse(data);
                        $.each(objData, function( key, val ) { // get arrays
                            console.log(val[0], val[1], val[2]);
                        });
                        //for (i in objData){
                        //    objData[i][0] = "<td><a href='"+objData[i][2]+"'>"+objData[i][0]+"</a></td>";
                        //}
                        //addDataToArticles(objData);
                        // alert("Data: " + data + "
    Status: " + status);
                    });
    });
    

    PHP:

    <?php
    
    $MyArticles = array (
     array("articleName1","count1","link1"),
     array("articleName2","count2","link2"),
     array("articleName3","count3","link3"),
     array("articleName4","count4","link4"),
     array("articleName5","count5","link5") 
    );
    
    echo json_encode($MyArticles); exit;
    

    You can run this code and check console, this row console.log(val[0], val[1], val[2]) returns you all data you want and you can use as you wish.

    In this code it returns:

    articleName1 count1 link1
    articleName2 count2 link2
    articleName3 count3 link3
    articleName4 count4 link4
    articleName5 count5 link5
    
    点赞 评论 复制链接分享