2017-01-16 75 views
0

我有很多項目,我想單擊使用ajax後發佈具體的項目信息。通常我通過屬性data-name,data-date等來存儲它的信息。我使用jquery通過.attr()來獲取它。如果文字太長或者每個項目都有一組文字{"Text1", "Text2","Text3"...."Text20"},我不知道該怎麼做。我無法將其存儲爲屬性。我無法弄清楚在哪裏放置它或如何&如何通過jQuery獲取?由ajax發送特定的php變量

我的項目看起來很簡單的像這樣

<div class="item"> 
    <a data-name="item1" data-available="1" data-color="blue">Item1</a> 
</div> 
<div class="item"> 
    <a data-name="item2" data-available="1" data-color="pink">Item2</a> 
</div> 

這是我的jQuery

jQuery(".item a").on('click', function() { 
      var url = "/test.php";   
      var item_name = jQuery(this).attr("data-name");  

      jQuery("#display").html("<img id='loading_gif' src='/loading.gif'>"); 
      jQuery("#display").load(url,{item_name:item_name}); 
      return false; 
    }); 
+0

如果你的屬性值是太長,你可能需要一個''存儲價值 –

回答

1

可以使用AJAX JSON數據發送到PHP文件,

jQuery(".item a").on('click', function() { 
    var available = $(this).attr("data-available"), 
     color = $(this).attr("data-color"); 

    $.ajax({ 
     url: 'url_to_your_phpfile.php', 
     type: 'post', 
     data: { 
      avail: available, 
      color: color 
     }, 
     success: function (data){ 
      console.log(data); // do something 
     } 
    }); 
} 

而且在你的PHP文件,你可以通過簡單地使用$_POST['avail']和來獲取變量

編輯

既然你想從PHP訪問您的數據到您的JavaScript,你可以存儲到一個JavaScript變量,例如

<?php 
    $products = array(
     array("id" => 1, "name" => "Item 1", "color" => "red", "desc" => "some large text..."), 
     array("id" => 2, "name" => "Item 2", "color" => "blue", "desc" => "some large text...") 
    ); 
    echo '<script>var products = '.json_encode($products).'</script>'; 
    // and then display 
    foreach($products as $product): 
     echo '<div class="item"><a data-id="'.$product->id.'" data-color="'.$product->color.'">'.$product->name.'</a></div>'; 
    endforeach; 

我假設你的JavaScript文件會始終處於頁面的頁腳區域,因此,您始終可以在您的JavaScript代碼上調用products變量。 在你的JS,你總是可以添加自定義功能,以找到您的產品通過其ID

function findProduct(id){ 
    var product = products.filter(function (product){ 
     if(product.id == id){ 
      return product; 
     } 
    }); 
    return products.length > 0 ? products[0] : product; 
} 

$('.item a').on('click', function() { 
    // get the id 
    var id = $(this).attr("data-id"); 
    // now, make a function that finds other data for that product with that ID 
    var product = findProduct(id); // finds a product from variable products 
    // product variable will now contain id, name, color, desc and 
    // can be accessed directly with product.id, product.desc, etc. 
}); 
+0

嗨dexterb,謝謝你的回答,我的意思是我已經可以發佈日期可用..但incase值太長文本或它是一個數組,我不知道如何存儲它,然後通過jquery得到它,如果我也把它作爲atrribute,那麼我的每個標籤都很大 – Yoona

+0

您好@Yoona,我在我的答案中添加了一個編輯,您不必將它們作爲屬性添加到您的每個'a'標籤之外'id'或您使用的任何唯一標識符。 – dexterb