我正在开发基于ajax的搜索,这是它将如何演示。我正在面对返回结果的问题。我需要显示结果2次。但它只展示一次。以下是我的HTML代码
<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 :(得分:0)
这行可能令人困惑的php:
while($ i&lt; 2){
return ['msg'] = $ get_product;
}
应该是$ return吗?使用像“返回”这样的保留字也是一件好事。
答案 1 :(得分:0)
请更改以下代码:
else {
$i=0;
$messageToReturn = "";
while($i<2) {
$messageToReturn .= $get_product; //Append to your variable
}
return json_encode($messageToReturn); //Returns the result
}
我建议将while更改为for循环。 在这种情况下,你会得到这个:
else {
$messageToReturn = "";
for($i = 0; $i < 2; $i++)
{
$messageToReturn .= $get_product; //Append to your variable
}
return json_encode($messageToReturn);
如果您知道需要重复的次数,请使用for循环。时间永无止境。所以你可以得到一个可能的堆栈溢出......