2012-06-01 111 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循环。这段时间永远不会结束。所以你可以得到一个可能的堆栈溢出...