我在使用 ajax json 请求和 Internet Explorer 时遇到问题。
特别是 ajax 请求的行为不正常。
我正在使用:
OpenCart 1.5.3.1
jquery-1.7.1.min.js
jquery-ui-1.8.16.custom.min.js
浏览器 9
PHP 5.2.9
这是请求函数:
function addToCart(product_id, quantity, option_id, option_value) {
quantity = typeof(quantity) != 'undefined' ? quantity : 1;
option_value = typeof(option_value) != 'undefined' ? option_value : 0;
option_id = typeof(option_id) != 'undefined' ? option_id : 0;
jQuery.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
cache: false,
data: 'product_id=' + product_id + '&quantity=' + quantity + '&option_id=' + option_id + '&option_value=' + option_value+'&rnd=' + Math.random(),
dataType: 'json',
success: function(jsonObj) {
$('.success, .warning, .attention, .information, .error').remove();
if (jsonObj['redirect']) {
location = jsonObj['redirect'];
}
if (jsonObj['success']) {
$('#notification').html('<div class="success" style="display: none;">' + jsonObj['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');
$('.success').fadeIn('slow');
$('#cart-total').html(jsonObj['total']);
$('html, body').animate({ scrollTop: 0 }, 'slow');
}
}
});
}
PHP 函数返回:
{"success":"Added to cart!","total":"1 product(s) - 52,48\u043b\u0432."}
这一切在 Chrome、FF 等中运行良好,但在 IE 中失败。
实际上 IE 不会触发“成功”事件。
我可以获得响应的唯一方法是通过错误处理程序。
然后 json 对象有一个 status = 200 和 statusText = OK
这是在 Chrome 中触发成功事件后的 json 对象:
jsonObj: Object
success: "Added to cart!"
total: "1 product(s) - 52.48лв."
__proto__: Object
从中使用“成功”和“总计”值。
这是在 Internet Explorer 中处理错误事件后的 json 对象:
responseText 是一个包含当前页面 html 源的字符串。
我试过 jQuery.ajaxSetup({cache: false});
但结果是一样的。
有人遇到过这个问题吗?或者有什么建议吗?
我没有更多的想法。
最佳答案
尝试对 url: 'index.php?route=checkout/cart/add' 使用绝对 url
问题是您的响应是 html 或 xml(我看到 xml 页面的开始标记( namespace 标记)后跟换行符,然后是(旧)html 起始标记)。
jQuery 需要 json。因此,这是一个解析错误,导致错误回调并没有达到预期的成功。
确保后端发送正确的信息并且调用的页面是正确的。您可以使用网络选项卡捕获调用以查找您的问题。
关于php - jQuery $.ajax 请求在 Internet Explorer 中收到错误响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12384644/