jQuery:因为换行和一些字符而导致ajax返回错误

时间:2013-08-06 06:45:51

标签: php jquery ajax

每个人,我都有问题。使用jQuery发出ajax请求。这是错误的。我尝试删除一些包含'换行符,双引号等'的变量。没有错误,一切都很好。怎么解决这个问题?

$.ajax({
    url: 'layout/owner/required/processing/get-product-data.php',
    cache: false,
    data: {idStr: thisProduct}
});

并且请求的php文件是:

<?php
header('Content-type: text/javascript');

$printData = '
var editData = {
    cat: "' . $cat . '",
    subcat: "' . $subcat . '",
    id: "' . $id . '",
    name: "' . $name . '",
    description: "' . $description . '",
    price: "' . $price . '",
    dlong: "' . $long . '",
    dwidth: "' . $width . '",
    dheight: "' . $height . '",
    spec: "' . $spec . '",
    fac: "' . $fac . '",
    rp: "' . $rp . '",
    cm: "' . $cm . '",
    color: "' . $color . '"
};
';

echo $printData;
?>

editData.description,editData.spec,editData.fac包含enter / linebreak字符,嗯说它们包含html

1 个答案:

答案 0 :(得分:3)

将它们放在PHP关联数组中,然后使用json_encode输出该数组。这将确保正确处理字符串中的字符。

,例如:

<?php
header('Content-type: text/javascript');
$a = array(
    cat =>  $cat,
    subcat =>  $subcat,
    id =>  $id,
    name =>  $name,
    description =>  $description,
    price =>  $price,
    dlong =>  $long,
    dwidth =>  $width,
    dheight =>  $height,
    spec =>  $spec,
    fac =>  $fac,
    rp =>  $rp,
    cm =>  $cm,
    color =>  $color
);
echo 'var editData = ' . json_encode($a) . ';';
?>