2012-06-01 108 views
2

我正在開發基於AJAX的搜索,這是它的演示。我面臨着返回結果中的問題。我需要顯示結果2次。但它只展示過一次。下面是我的HTML代碼通過AJAX,PHP和MYSQL傳遞參數時返回多個值

<form action="" method="post" id="demoform"> 
<select style="width:250px;padding:5px 0px;color:#f1eedb;" name="product" class="product"> 
    <option>TENNIS</option> 
    <option>FOOTBALL</option> 
    <option>SWIMMING</option> 
</select> 
</form> 
<div id="result">Display Result Here</div> 

我使用下面的腳本的Ajax檢索數據: -

$(".product").change(function(){ 
      $.ajax({ 
       type : 'POST', 
       url : 'post.php', 
       dataType : 'json', 
       data: { 
        product : $(".product option:selected").text(), 
       }, 
       success : function(data){ 
        $('#result').removeClass().addClass((data.error === true) ? 'error' : 'success') 
         .html(data.msg).show(); 
        if (data.error === true) 
         $('#demoForm').show(); 
       }, 
       error : function(XMLHttpRequest, textStatus, errorThrown) { 
        $('#result').removeClass().addClass('error') 
         .text('There was an error.').show(500); 
        $('#demoForm').show(); 
       } 
      }); 
     }); 

的post.php中的文件具有下面的代碼: -

<?php 
require('connect.php'); 
$get_select = $_POST[product]; 
if($get_product!='FOOTBALL'){ 
    $return['error'] = true; 
    return['msg'] = 'Incorrect Selection'; 
    echo json_encode(return); 
} 
else { 
    $return['error'] = false; 
    $i=0; 
    while($i<2) { 
    return['msg'] = $get_product; 
    } 
    echo json_encode(return);//Returns only one result. 
} 
?> 

我需要顯示結果兩次爲「CRICKET CRICKET」,但它只顯示一次。 我該怎麼做才能得到兩個結果。

+0

我有幾個關於PHP的問題:(1)$ get_product不存在 - 你的意思是$ get_select? (2)所有那些你說'返回'的地方你是不是指'$ return'? (3)你爲什麼要將$ get_product放入$ return ['msg']兩次 - 你認爲你會得到兩個結果嗎?如果你選擇'足球',你應該回到{'error':'false','msg':'FOOTBALL'}。 –

+0

@ adwitya-media看看答案並標記正確的答案:) –

回答

0

是否有可能這條線是混亂的PHP:

而($ I < 2){
返回[ 'MSG'] = $ get_product;
}

應該是$ return嗎?使用像'return'這樣的保留字也是非常有趣的。

0

請更改下面的代碼:

else { 
    $i=0; 
    $messageToReturn = ""; 
    while($i<2) { 
    $messageToReturn .= $get_product; //Append to your variable 
    } 
    return json_encode($messageToReturn); //Returns the result 
} 

我建議而改變到一個for循環。 在這種情況下,你會得到這樣的:

else { 
$messageToReturn = ""; 
for($i = 0; $i < 2; $i++) 
{ 
    $messageToReturn .= $get_product; //Append to your variable 
} 
return json_encode($messageToReturn); 

如果你知道你需要重複多次,使用for循環。這段時間永遠不會結束。所以你可以得到一個可能的堆棧溢出...