我想在jquery代码中使用php脚本。这里我把php脚本在我的jquery,但我的jquery函数不工作,然后。这是正确的方式把php脚本在一个jquery函数
<script type="text/javascript">
$(function() {
var count2=1;
$('a#addTelefono').click(function() {
count2 +=1;
$('<p><div style="float:left;width: 100%;"><select name="product_id[]" ><?php $sql=mysql_query("SELECT * FROM tbl_product"); while($res=mysql_fetch_array($sql)){ echo "<option value='".$res['id']."'>".$res['product_name']."</option>";}?></select><input type="text" name="discount[]" placeholder="discount ' + count2 + '" style="margin-left: 8px;" id="discount_' + count2 + '" />%<a href="#" class="remove" id="elimina"><img src="images/cross.png"></a></div></p>').fadeIn("slow").appendTo('#extendTelefono');
i++;
return false;
});
//fadeout selected item and remove
$('.remove').live('click', function() {
$(this).parent().fadeOut(300, function(){
$(this).remove();
return false;
});
});
});
</script>
您必须分两步完成,并将php代码与jQuery分开,以提高可读性:
$sql = mysql_query("SELECT * FROM tbl_product");
while($res=mysql_fetch_array($sql))
{
$contents .= "<option value='".$res['id']."'>".$res['product_name']."</option>";
}
$('<select name="product_id[]" ><?php echo($contents); ?></select> .....');
另外,要小心$res['product_name']中的字符:如果你的产品名中有引号(所以你必须转义它),它可能会失败。
此外,mysql_*已弃用,参见mysqli_*或PDO。