2010-07-24 64 views
2

我向php文件发送了一个post请求,该文件使MySQL查询并遍历响应。在迭代过程中,它会显示一个字符串,我希望每次迭代都要逐个将它带入jQuery中。JQuery Ajax在创建响应时引入响应

因此,对于每个回声,我想要一个成功值,以便用户不必等待所有迭代完成。

compSelect类是一个select元素。

我想要追加选项作为回声的味精通过味精,并非所有在一个味精。

眼下成功味精看起来像name1name2name3

我想每个MSG是个人的名字。

中的JavaScript

$.ajax({ 
       type: "POST", 
       cache: false, 
       url: "class.GetMiscInfo.php", 
       data: "getNames=1&name=Jack", 
       dataType: "html", 
       success: function(msg) { 

        $('.compSelect').append("<option value='" + msg +"'>" + msg +"</option>"); 

       } 
      }); 

的PHP/MySQL的

class GetMiscInfo 
    {   
     public static function getNames($name) 
     { 
      $res = mysql_query("SELECT names.name FROM names WHERE names.name='$name'"); 

      while($row = mysql_fetch_assoc($res)) 
      { 
       echo $row['name']; 
      } 
     }  
    } 

    if(isset($_REQUEST['getNames'])) 
     GetMiscInfo::getNames($_REQUEST['name']); 

我知道我可以用绳子一样〜然后就分裂反应,但对于更复杂的查询,我想它们分开不必等待。

我想我只是缺少一些与Ajax相关的知识来获得我想要的。

回答

1

而是在每次迭代呼应出每个名字的,他们最多存储阵列中的:

$data = array('names' => array()); 
while($row = mysql_fetch_assoc($res)) 
{ 
    $data['names'][] = $row['name']; 
} 

// Once the loop has completed, `json_encode` the array and send it to the client 
// optionally, set an 'error' offset if there is no data, or something bad happened 
if(empty($data['names'])) { 
    $data['error'] = 'No data to return'; 
} 
echo json_encode($data); 

处理它在客户端上这样的:

$.ajax({ 
    type: "POST", 
    dataType: "json", // the data we are expecting is JSON 
    cache: false, 
    url: "class.GetMiscInfo.php", 
    data: "getNames=1&name=Jack", 
    success: function(json) { 
     if(json.error) { 
      alert('error: ' + json.error); 
     } 
     $.each(json.name, function(Index, val) { 
      $('.compSelect').append("<option value='" + val +"'>" + val +"</option>"); 
     }); 
    } 
}); 
2

你正在请求的是从服务器流式传输数据。这不是jQuery架构师使用AJAX方法的方式。这不是最关键的方式。

就这样说,你所做的事情在数据方面相当微不足道。我认为流式传输会过度。我的建议是让PHP脚本返回JSON并将您的jQuery代码更改为使用getJSON

查看PHP JSON functionsjQuery's JSON methods