通过ajax发送数据时会自动添加转义字符

时间:2014-06-18 10:17:20

标签: php jquery ajax

我想使用link元素的id发送SQL条件语句,该元素是由php文件生成的产品的类别,并加载回具有类load_area的div。我使用.attr()方法获取类别,然后将此数据作为字符串{' category ='" + cat +"'}发送到php文件。发送的字符串应为

category="bag"

但这是我在php文件中打印的结果

category='\"bag\"'

正如您所看到的那样,php文件会自动将转义字符添加到我发送给它的字符串中,并且查询无法成功处理。我很沮丧,试图找到解决问题的正确方法。所以请帮忙......

这是我的HTML

<a id="bag" href="#">Bag</a>
<div class="load_area"></div>

这是javaScript

$(document).ready(function() {
    $('a').click(function() {
        var cat = $(this).attr('id');
        $('.load_area').load('controllers/genproduct.php', {'condition':'category='"+cat+"'});
    });
});

这是我的php脚本

<?php
$condition = explode("=", $_POST['condition']); // Get condition
$limit = $_POST['limit']; // Get limit
require_once("../engines/store_manager.class.php");
$store = new store_manager(mysql_connect("localhost", "root", "1234"), "gemalong",     "cart", "products");
if(isset($condition) || $condition != "") {
if(isset($limit) || $limit != "") {
    $getquery = $store->product_gen($condition, $limit);
}
else {
    $getquery = $store->product_gen($condition);
}
}
else {
$getquery = $store->product_gen();
}
while($data=mysql_fetch_array($getquery)) {
$pid = $data['id'];
$pname = $data['name'];
$pdesc = $data['description'];
$pprice = $data['price'];
$ppix = $data['pix'];
// Start generating view
echo "<div class='each_product'>";
    echo "<div class='img_container'>";
        echo "<a id='ppixlink".$pid."' href='#' alt='".$pname."'><img      src='".$ppix."' title='".$pname."' /></a>";
    echo "</div>";
    echo "<p class='product_name'><a id='plink".$pid."' href='#'     alt='".$pname."'>".$pname."</a></p>";
    echo "<div class='down_pb clearfix'>";
        echo "<p>$ ".$pprice."</p>";
        echo "<button type='button' id='productaddbtn".$pid."' class='addcart-btn'>Add to cart</button>";
    echo "</div>";
echo "</div>";
}
// Close connection
mysql_close();
?>

1 个答案:

答案 0 :(得分:0)

不要发送需要在php中操作的字符串,而是发送两个字段:

//js
$('.load_area').load('controllers/genproduct.php', {field: 'category', value: cat});

//php
$condition = array($_POST['field'], $_POST['value']);