2017-01-16 1 views
0

私は多くのアイテムを持っています。私はクリック後に特定のアイテム情報を投稿したいと思います。通常、私はその情報を属性データ名、データ日付などで保存します。私はjqueryを使って.attr()で取得します。テキストが長すぎる場合、または各アイテムにテキストの配列がある場合は、私はそれを行う方法がわかりません{"Text1", "Text2","Text3"...."Text20"}。私はそれを属性として保存することはできません。私はそれをどこに置くか、またはどのようにすればわからないのですか?& jQueryの入手方法?特定のphp変数をajaxで送信する

私のアイテムがこの

<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> 

のように非常に単純に見えるこれはあなたが、AJAXを使用して、あなたの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 
     } 
    }); 
} 

そして中にJSONデータを送信することができ、私の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

そのIDによって、あなたの製品を見つけるためにカスタム関数を追加することができます値 –

答えて

1

ですあなたのPHPファイルでは、単純に$_POST['avail']とを使って変数を取得できます

EDIT

あなたがJavaScriptにPHPからデータにアクセスしたいので、あなたは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で 、あなたは常にあなたの属性値が長すぎる場合、あなたが店に `の`を必要とするかもしれ

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、回答ありがとう、私はすでに日付を使用できる..を投稿することができますが、値が大きすぎるテキストまたは配列です、私はそれを保存する方法を知らないjquery、私もそれを寄付として置いた場合、私のタグは非常に大きいです – Yoona

+0

こんにちは@Yoona、私は私の答えに編集を追加しました。あなたはあなたの 'a'タグのそれぞれに属性としてそれらを置く必要はありません'id'または使用する一意の識別子。 – dexterb

関連する問題