可以使用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.
});
如果你的屬性值是太長,你可能需要一個''存儲價值 –