douji6667 2015-04-23 06:53
浏览 36
已采纳

如何通过php和ajax将html添加到返回的json对象中

I was wondering how to add a html link to each JSON item as it is returned.

php file

//relevant code, $result contains sql query with records from a search
    $records = array();
    while($array = mysqli_fetch_array($result))
     {
        $records[] = $array;
     }
   echo(json_encode($records));

Output html via ajax

function responseReceived(e){
        document.getElementById('response').innerHTML = e.target.responseText;
    }

Response is a div tag. So I was wondering how would I add html link (to another page) to each item within the json. Because at the moment it outputs json but it's not allowing me to add html. This is the current output, which is as expected due to me entering data via a form, I just want to add a small html link next to him.

[{"0":"1115","ID":"1115","1":"john","name":"john","2":"male","type":"male","3":"berk","country":"berk","4":"aus","region":"aus","5":"32.43","lon":"32.43","6":"32.54","lat":"32.54","7":"nothing to say","description":"nothing to say"}]

Thanks, in advance.

  • 写回答

2条回答 默认 最新

  • doswy02440 2015-04-23 07:20
    关注

    Where will you get the link from?

    Is the returned data the link or is the returned data some text that should be formatted as a link?

    If it's the second one, you need to get the link from somewhere.

    What you could do is storing some sort of link/id in the database and print that out in the json so it will output something like:

    [{"url": "http://example.com", "content": "This is a link!"}]
    

    I presume that you know how to do a ajax call, so let's just continue to the formatting:

    // Let's make a function
    function createLinks(json){
    
        // Let's parse the JSON first (if it's a string)
        json = JSON.parse(json);
    
        // Loop through all the elements
        for(var i = 0; i < json.length; i++){
    
            // Check if the fields exist
            if(json[i].url && json[i].content){
    
                // Creating a tag
                var a = document.createElement("a");
    
                // Let's add the values to the a tag
                a.href = json[i].url;
                a.textContent = json[i].content;
                // ^ or innerHTML if you want to have HTML code there
    
                // Appending to body element (just for this example)
                document.body.appendChild(a);
    
            }
    
        }
    
    }
    

    I hope it helps!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测