0
我遇到了一些問題,顯示通過ajax請求從php文件傳遞的錯誤消息。jQuery Ajax Calculator問題
問題是,當我收到少於3個應該顯示在無序列表中的錯誤消息時。我不想顯示任何「未定義」變量 - 這就是爲什麼我沒有通過一條語句將它們添加到無序列表中的原因。
有什麼建議嗎?
calculator.html
<div id="calculator">
<form>
<input type="text" name="years"/>
<label>How many years have you smoked for?</label><br />
<input type="text" name="smokes"/>
<label>How many cigarettes do you smoke each day?</label><br />
<input type="text" name="price"/>
<label>How much do you spend on each pack of cigarettes?</label><br />
<input type="submit" value="Show My Totals" name="submit" />
</form>
<div id="result"></div>
</div><!-- end calculator -->
calculator.js
$(function(){
$("#calculator form").submit(function(){
dataString = $("#calculator form").serialize();
$.ajax({
type: "POST",
url: "./calc.php",
data: dataString,
dataType: "json",
success: function(data) {
if(data.totalSmoked != null && data.totalSmoked != undefined &&
data.totalCost != null && data.totalCost != undefined &&
data.totalWeight != null && data.totalWeight != undefined)
{
$("#calculator #result").html("<ul><li>" + data.totalSmoked + "</li><li>" + data.totalCost + "</li><li>" + data.totalWeight + "</li></ul>");
}
else
{
$("#calculator #result").html("<ul>");
if(data.yearsError != null && data.yearsError != undefined) {
$("#calculator #result ul").html("<li>" + data.yearsError + "</li>");
}
if(data.smokesError != null && data.smokesError != undefined) {
$("#calculator #result ul").html("<li>" + data.smokesError + "</li>");
}
if(data.costError != null && data.costError != undefined) {
$("#calculator #result ul").html("<li>" + data.costError + "</li>");
}
$("#calculator #result").html("</ul>");
/**** If I replace the above content within the 'else' block, it works however - This will display an "undefined" variable if there are less than 3 errors ****/
//$("#calculator #result").html("<ul><li>" + data.yearsError + "</li><li>" + data.smokesError + "</li><li>" + data.costError + "</li></ul>");
}
}
});
return false;
});
});
Calculator.php中
$yearsSmoked = $_POST['years'];
$smokesPerDay = $_POST['smokes'];
$costPerPack = $_POST['price'];
$errors = array();
$results = array();
/**
*
*
* A bunch of error checking here...
*
*
*/
if(!empty($results)) {
echo json_encode($results);
}
elseif(!empty($errors)) {
echo json_encode($errors);
}
UPDATE
我想它不起作用,因爲我在我的PHP文件中指定了數組鍵。把這個添加到我的else塊中工作...有種醜陋的方式。
if(data['yearsError'] != undefined) {
$("#calculator #result ul").append("<li>" + data['yearsError'] + "</li>");
}
if(data['smokesError'] != undefined) {
$("#calculator #result ul").append("<li>" + data['smokesError'] + "</li>");
}
if(data['costError'] != undefined) {
$("#calculator #result ul").append("<li>" + data['costError'] + "</li>");
}
感謝您的提示馬克。我已經嘗試了for循環,並且只是再次嘗試並在我的錯誤控制檯中收到此消息:data.errors未定義。 我對json不太熟悉,似乎無法以這種方式訪問數組。 – 2010-08-25 04:06:18
嘗試用'alert()'或'console.log'吐出返回的json數據並查看實際返回的內容。 – 2010-08-25 13:55:50