2015-04-23 41 views
2

我想知道如何在每个JSON项目返回时添加一个html链接。通过AJAX如何通过php和ajax将html添加到返回的json对象

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

输出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

by loop?我可以看看你的json是怎么样的? –

+0

刚刚添加了我的json通过搜索表单的外观。我真的不知道为什么,但当我试图通过循环添加它,它停止工作。所以我一定在做一些愚蠢的错误。 – Steven

+1

你没有使用'mysqli_fetch_array'返回的结果 –

回答

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

     } 

    } 

} 

我希望它有帮助!

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>'; 
}