2017-01-12 52 views
-3

忽略所有被觸擊的文本使用PHP和AJAX驗證條件

這場爭鬥是真實的。在一個index.php文件與大多HTML代碼我有充當按鈕的多個<span>元件與class="delete_this"

<ul id="products"> 
    <li class="product"> 
     <!-- more code --> 
     <div class="select-delete"> 
      <span class="delete-product delete_this" title="Delete"></span> 
     </div> 
    </li> 
    <li class="product"> 
     <!-- more code --> 
     <div class="select-delete"> 
      <span class="delete-product delete_this" title="Delete"></span> 
     </div> 
    </li> 
    <li class="product"> 
     <!-- more code --> 
     <div class="select-delete"> 
      <span class="delete-product delete_this" title="Delete"></span> 
     </div> 
    </li> 
</ul> 

當(技術上任何)與class="delete_this"被點擊任何<span>元件,一個jQuery AJAX請求時:

// The exact following line is a simple on click function, it's a little different 
// than the usual since I'm loading .delete_this also dynamically. It runs when you click 
// on any element *.delete_this 
$("#products").on("click", ".delete_this", function(event) { 
    var $count = $("#products > li").length; 
    $.ajax({ 
     method: "POST", 
     url: "validate_existence.php", 
     // The following sends some data to the validate_existence.php file 
     data: {"quantity_of_products": $count}, 

 success:function(html) { 
      if (html == "true") { 
       // condition met 
      } else { 
       // condition not met 
      } 
     } 

}); 
}); 

因此,在<span class="delete_this">用戶點擊,則:(1)變量被定義和(2)的AJAX請求,發送作爲數據變量的值。

現在,在validate_existence.php我想要使用if() {}進行條件語句。將待測試的條件是,如果在AJAX請求中發送的可變$count等於1:

<?php 

if ($_POST['quantity_of_products'] = 1) { // Edit: thanks everyone for saying to use two equal symbols 
    // Run code if criteria is met 
} else { 
    // Run code if criteria is not met 
} 

?> 

問題是內部的index.php在// condition not met代碼始終運行,即使標準WASN見了(AKA $_POST['quantity_of_products'] /= 1)。

我最有可能丟失在validate_existence.php文件的東西,或者在index.php使用function(html)不正確。

+0

你可以使用Fi調試您的ajax reBug – Akshay

+3

$ _POST [ 'quantity_of_products'] = 1,則必須使用== – JYoThI

+0

第一打印所述'的print_r($ _ POST)是指派值到$ _POST [ 'quantity_of_products']變量;'變量在你'validate_existence.php'文件並檢查你得到了什麼? –

回答

3

更改以下行:

if($_POST['quantity_of_products'] = 1) // This is assignment 

if($_POST['quantity_of_products'] == 1) // This is condition checking 
2

$_POST['quantity_of_products'] = 1是指派值到$_POST['quantity_of_products']變量。所以你必須使用這樣$_POST['quantity_of_products']==1

if($_POST['quantity_of_products'] == 1) 
+1

不是響應字符串嗎? '成功回調函數傳遞返回的數據,這將是一個XML根元素或一個文本字符串,具體取決於響應的MIME類型。' – chris85

+0

能夠獲取字符串作爲響應,但他返回的是boolen值,所以我這樣說 – JYoThI

+0

是的,我同意你@ chris85 – JYoThI

1

第一點調試POST值的(至少對我來說)是爲了確認該服務正在接收數據,並確認它接收。 最簡單的用下面這樣做:

print_r($_POST['quantity_of_products']; 

echo $_POST['quantity_of_products']; 
0

我認爲最好的辦法是使用三元運算符:

<?php 

if ($_POST['quantity_of_products'] = 1) { 
    echo true; 
} else { 
    echo false; 
} 

?> 

替換代碼

<?php 
$test = $_POST['quantity_of_products'] == 1? true: false; 
echo $test;