2010-07-24 32 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