在Ajax中获取多个PHP数组并创建DIV标记

时间:2013-11-29 13:33:18

标签: javascript php jquery ajax

我从数据库返回多个条目并将它们放入数组中;然而在第二部分涉及使用ajax和循环解析它们我不成功。

PHP数组:

$historyl = array();
while($h=mysql_fetch_assoc($sql)){
   $historyl[] = $h;
}
foreach ($historyl as $his){
    echo json_encode( array('type' => 1, 'picture' => "{$his[picture]}", 'artist' => "{$his[artist]}", 'title' => "{$his[title]}")) . '%#%';
}

我正在通过%#%吐出每个条目。

useHttpResponse:

var lastResponse = '';

function useHttpResponse() {
    if (http.readyState == 3) {
        // Get the original response before we edit it
        var originalResponse = http.responseText;
        // Replace the found last response in our original response with nothing(basically editing out the last response)
        var newResponse = originalResponse.replace(lastResponse, '');
        // Add our new response to the last response
        lastResponse += newResponse;
        var responses = newResponse.split("%#%");
        $.each(responses, function (index, value) {

            if (value != '') {

                var textout = eval('(' + value + ')'); 
                document.getElementById('title').innerHTML =  textout.title;
                document.getElementById('artist').innerHTML =  textout.artist;
                document.getElementById('picture').innerHTML = http://blu.com/textout.picture;
            }
        });
    }
}

在Ajax部分,我需要以某种方式将结果放在DIV中,如下所示,以便稍后我可以通过另一个文件中的div标签来调用它们。

document.getElementById('title').innerHTML =  textout.title;
document.getElementById('artist').innerHTML =  textout.artist;
document.getElementById('picture').innerHTML = http://blu.com/textout.picture;

有谁知道我应该如何修复div部分?

编辑: 这是最后的样子;但是仍然没有运气!

<html>
<head>
<title>Recently</title>

<script language="JavaScript">
 var http = getXMLHTTPRequest();
var counter;

function getXMLHTTPRequest() {
try {
 req = new XMLHttpRequest();
} catch(err1) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (err2) {
  try {
  req = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (err3) {
    req = false;
  }
}
}
return req;
}
///////
function getServerText() {
  var myurl = 'http://blu.com/recentlyajax.php'; // enter the full path to the aj_TimeRemain.php path
  var modurl = myurl;
  http.open("GET", modurl, true);
  http.onreadystatechange = useHttpResponse;
  http.send(null);
}
var lastResponse = '';
function useHttpResponse()
{

  if(http.readyState == 3)
  {
    // Get the original response before we edit it
      var originalResponse = http.responseText;
      // Replace the found last response in our original response with nothing(basically editing out the last response)
      var newResponse = originalResponse.replace(lastResponse, '');
      // Add our new response to the last response
      lastResponse += newResponse;
      var responses = newResponse.split("%#%");
      var histItems = JSON.parse(originalResponse);

    // histItems is now a regular array, containing objects with title,artist,picture fields
    $.each(histItems, function(i, item){
        document.getElementById('title').innerHTML =  item.title;
        document.getElementById('artist').innerHTML =  item.artist;
        document.getElementById('picture').innerHTML = "http://blu.com/"+item.picture;
    });


   }

}

$.ajax({
url: "http://blu.com/recentlyajax.php",
data: {arg1: val1, arg2: val2, ...},
dataType: "json",  // <- this instructs jQuery to parse answer as json
success: function(histItems){
    $.each(histItems, function(i, item){
        document.getElementById('title').innerHTML =  item.title;
        document.getElementById('artist').innerHTML =  item.artist;
        document.getElementById('picture').innerHTML = "http://blu.com/"+item.picture;
    });
}
});

          </script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><style type="text/css">
<!--
body,td,th {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 12px;
color: #999999;
 }
-->
</style></head>
<body>
<script language="JavaScript">
var $div = $('<div></div>')
.addClass('histItem')
.append('<span class="title">'+item.title+'</span>');
$('#histList').append( $div );
</script>
</body>
</html>

3 个答案:

答案 0 :(得分:0)

document.getElementById('picture').innerHTML = http://blu.com/textout.picture;

更改为

document.getElementById('picture').innerHTML = 'http://blu.com/' + textout.picture;

答案 1 :(得分:0)

从数据库返回的数据必须以json格式格式化,然后返回。使用javascript / jquery很容易从json格式和进程获取数据。 例如:

var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );

答案 2 :(得分:0)

正如所建议的,完全使用json:

//PHP
$historyl = array();
while($h=mysql_fetch_assoc($sql)){
   $historyl[] = $h;
}
$histItems = array();
foreach ($historyl as $his){
    $histItems[] = array('type' => 1, 'picture' => $his['picture'], 'artist' => $his['artist'], 'title' => $his['title']));
}
echo json_encode($histItems);


// javascript
var histItems = JSON.parse(originalResponse);

// histItems is now a regular array, containing objects with title,artist,picture fields
$.each(histItems, function(i, item){
    document.getElementById('title').innerHTML =  item.title;
    document.getElementById('artist').innerHTML =  item.artist;
    document.getElementById('picture').innerHTML = "http://blu.com/"+item.picture;
});

// javascript, using jQuery :
$.ajax({
    url: "url/to/fetch/json.php",
    data: {arg1: val1, arg2: val2, ...},
    dataType: "json",  // <- this instructs jQuery to parse answer as json
    success: function(histItems){
        $.each(histItems, function(i, item){
            document.getElementById('title').innerHTML =  item.title;
            document.getElementById('artist').innerHTML =  item.artist;
            document.getElementById('picture').innerHTML = "http://blu.com/"+item.picture;
        });
    }
});

要创建div:$(validHtml)将创建一个新节点,而不是选择现有节点。然后,您可以在该节点上使用常规jQuery操纵器:

var $div = $('<div></div>')
       .addClass('histItem')
       .append('<span class="title">'+item.title+'</span>')
       .append( ... )...;
// you then need to insert this new node somewhere on your page :
$('#histList').append( $div );