3

我有一个会话数组$_SESSION['Cartquantity']。在第 200 行的 php 文件中,我将此数组存储在变量$QtyArray 中

$QtyArray = $_SESSION['Cartquantity'] ;

然后我在json中对数组进行编码以在 js 文件中使用它

echo "var cartQty = " . json_encode($QtyArray) . ";" ; (on line 201)

现在通过AJAX,我以同样的方式更新第 120 行的会话数组

$QtyArray = $_SESSION['Cartquantity'] ;                (on line 120)
echo "var cartQty = " . json_encode($QtyArray) . ";" ; (on line 121)

这是我调用文件的javascript代码

$.ajax({
                    url:'index.php',
                    cache:false,
                    datatype:'json',
                    data:{ q: "add_card", item_id: id, item_qty: qty,stop:'1' },
                    success:function(data){
                        $("#cart_quanity").html(parseFloat($("#cart_quanity").html()))
                    }
                });
        return false ;  

数组显然正在更新,因为我可以在萤火虫的控制台上看到它。但是当我在 js 文件中获取这个值时,值并没有改变。如果我重新加载通过 ajax 更新此值的页面,然后查看数量,它正在发生变化。为什么会这样?

请帮忙!!!

4

1 回答 1

0

ajax 请求的服务器端处理程序应该只返回数据文字本身。
在客户端解析该数据,然后在那里处理它 - 不是作为“完整”的 javascript 片段,而只是作为数据对象。JQuery 在解析部分为您提供支持。只需让它自动猜测响应的类型或在调用 $.ajax 或 $.post 时定义它。

$.post(url, data, function(response) {
  // you cann assume response to be an object 
  // containing the data from the json-response of the server
}, "json");

独立的例子(没有做任何有用的事情):

<?php
if ( isset($_POST['foo']) ) {
    // the client requests a new item
    $rv = array(
      'status'=>'ok',
      'value'=>rand(1,10)
    );
    header('Content-type: application/json');
    echo json_encode($rv);
    die;    
}
?>
<html>
    <head>
        <title>...</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script>
            $(document).ready(function() {
                var total = 0;
                $(".foo").on("click", function() {
                    $.post("?", { foo: true }, function(data) {
                        if ( data.status && "ok"==data.status ) {
                            var newValue = data.value;
                            total += newValue;
                            $("#output").append("+ "+newValue+" = "+total+"<br />");
                        }
                    }, "json");
                });
            });
        </script>
    </head>
    <body>
        <button class="foo">click</button>
        <div id="output">0<br /></div>
    </body>
</html>
于 2013-03-11T14:55:26.980 回答