我想知道如何在返回时为每个JSON项添加一个html链接。
php文件
//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));
通过ajax输出html
function responseReceived(e){
document.getElementById('response').innerHTML = e.target.responseText;
}
响应是div
标记。所以我想知道如何将html
链接(到另一个页面)添加到json
中的每个项目。因为目前它输出json
,但它不允许我添加html
。
这是当前输出,由于我通过表单输入数据,这是预期的,我只想在他旁边添加一个小html
链接。
[{"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"}]
提前谢谢。
答案 0 :(得分:0)
你从哪里获得链接?
返回的数据是链接还是返回的数据应该格式化为链接的文本?
如果是第二个,你需要从某个地方获取链接。
你可以做的是在数据库中存储某种链接/ id并在json中打印出来,这样就会输出如下内容:
[{"url": "http://example.com", "content": "This is a link!"}]
我认为你知道如何进行ajax调用,所以让我们继续格式化:
// 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);
}
}
}
我希望它有所帮助!
答案 1 :(得分:0)
这个简单的代码添加了每个数组项的链接。如果要将其转换为HTML,只需创建HTML字符串,然后可以使用innerHTML插入它。
var obj = JSON.parse('[{"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"},{"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":"ggg"}]');
for (var i = 0; i < obj.length; i++) {
obj[i].link = '<a href="http://www.google.com">Google</a>';
}