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条)

报告相同问题?