我可以使用 foreach 循环来发送 ajax 调用的响应吗?


Can i use foreach loop to send response for an ajax call?

对不起,如果这是一个愚蠢的问题。我正在对 php 脚本进行 ajax 调用以获取一些数据,这是我的代码

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function loadDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
var finallydata=JSON.parse(xmlhttp.responseText);
document.getElementById("myDiv").innerHTML=typeof finallydata;
 }
  }
var url='http://localhost/path/to/my/script';
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadDoc()">Change Content</button>
</body>
</html>

这是我在 YII 中的 php 脚本

if($timevalue != 0)
        {
            $model=new Products;
            $receivedata=$model->retrieveresult($timevalue);
            foreach($receivedata as $finaldata)
            {
                  header('Content-Type: application/json');
            echo json_encode(array('table'=>'products',array('productId'=>$finaldata->productId,'productName'=>$finaldata->productName,'Creation_date'=>$finaldata->Creation_date)));
            }
        }

现在,由于我必须发送多个数据记录,但一个接一个,那么我可以使用它 foreach 循环吗?我是新手,不知道它是否有效。 有人可以帮忙吗?

不能发送多个内容类型标头。无论如何,发送多行 JSON 都没有意义。为什么不立即echo json_encode($receivedata);?或者,在你的foreach循环中:$results[] = array( /* Your stuff here */ );和循环echo json_encode($results);之后,这将发送一个数组数组

你的Javascript代码div输入响应的类型(你正在使用typeof),这将读出为"对象" - 不是你期望的,但你的JSON响应是JS的对象,所以是有道理的。你应该考虑一旦你在那里得到数据,你想用JS中的数组做什么。