为什么jQuery.parseJSON会影响方法负载


Why jQuery.parseJSON affect to the method load?

我正在尝试在ajax之后加载页面的一部分。。。所以我在java脚本中使用这段代码之后,根据返回的数据:

var getPrice = $(this).closest('li');
var price = getPrice.next();
var id = $(this).attr('data-id');
    $.ajaxSetup({
        url: "do_cart_actions.php?action=qty",
        type: 'POST', 
        data: data, 
        success: function(data) {
            var result = jQuery.parseJSON(data);
            if(result.good == 1) {
                price.fadeOut('fast', function() {
                    price.load('show_cart.php .item_price_'+id, function() {
                        price.fadeIn('fast');
                    });
                });
            }
        }
   });
   $.ajax();

我的php文件返回这个:

echo '{ "good":"1" , "qty":"'. $_POST['a'] .'" }';

当我尝试此操作时,chrome返回以下错误:

Uncaught SyntaxError: Unexpected token <

奇怪的是,代码与fadeOut一起工作,如果我删除.load,也与fadeIn一起工作。。。。如果我删除var result并从我的php文件中返回一个数字'2',并修改我的javascript,如下所示:

if(data == 2) {
        price.fadeOut('fast', function() {
            price.load('show_cart.php .item_price_'+id, function() {
                price.fadeIn('fast');
            });
        });
}

现在,一切又恢复了正常。所以我唯一的理论是,加载方法和jQuery.parseJSON 可能有问题

知道吗?

在PHP中排名第一。。取而代之的是

echo '{ "good":"1" , "qty":"'. $_POST['a'] .'" }';

您可以很容易地将json函数用作:

echo json_encode(array('good'=>1,'qty'=>$_POST['a']));

在您的javascript上排名第二:

success: function(data) {
    var result = jQuery.parseJSON(data);

您不需要解析数据,因为它已经是JSON格式了。

为了确保这一点,在向PHP代码回显json_encode之前,可以将和json头添加为:

header('Content-Type: application/json');

P.S!!!

不要使用ajaxSetup来处理您的请求!它将影响您发出的任何下一个ajax请求,这可能会在以后成为一个问题!

服务器端:

echo json_encode(array('good'=>1,'qty'=>$_POST['a']));

客户端:使用数据类型

$.ajaxSetup({
            url: "do_cart_actions.php?action=qty",
            type: 'POST', 
            data: data, 
            dataType : 'json',
            success: function(result) {
            if(result.good == 1) {
                price.fadeOut('fast', function() {
                    price.load('show_cart.php .item_price_'+id, function() {
                        price.fadeIn('fast');
                    });
                });
            }
        }
   });

它是什么?

price.load('show_cart.php .item_price_'+id, // ...

为什么要将PHP文件的路径和CSS选择器结合起来?

我可能猜测它试图加载给定的URL,比如show_cart.php .item_price_3,但没有找到这样的页面(显然),返回了404错误的HTML页面,由于标签打开<,该页面没有被解析为JSON。打开开发人员控制台的Network选项卡,您会发现您提出了一个错误的URL请求。

另外,为什么要使用$.ajaxSetup?对于特定的AJAX调用,您应该使用:

$.ajax({
    url: "do_cart_actions.php?action=qty",
    type: 'POST', 
    data: data, 
    success: function(data) {
        var result = jQuery.parseJSON(data);
        if(result.good == 1) {
            price.fadeOut('fast', function() {
                price.load('show_cart.php .item_price_'+id, function() {
                    price.fadeIn('fast');
                });
            });
        }
    }

});

另外,请注意,success在最新的jQuery版本中已弃用。请改用.done()处理程序。

你试过在console.log()中显示吗?

结果的内容

var result = jQuery.parseJSON(data);

以防万一。