JSON.Parse问题 - 控制台在DOCTYPE中显示错误

时间:2015-07-31 06:00:37

标签: javascript jquery ajax json

我正在尝试使用JQuery将一些JSON数据写入div:

var obj = JSON.parse(data);
$('#container').html(obj.services.service[0].code);

但是我收到错误,说我的DOCTYPE中存在语法错误:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

我在其他帖子中读到这可能是因为JSON对象周围的引号。我试图在JSON对象周围添加不​​同的引号,但没有运气,例如:var obj = JSON.parse("'" + data + "'");

我不确定如何解决这个问题。有人能指出我正确的方向吗?

由于

JSON数据如下所示:

{
  "services": {
    "service" : [
      {
        "code": "AUS_PARCEL_REGULAR",
        "name": "Parcel Post (your own packaging)",
        "speed": 2,
        "price": 6.95,
        "max_extra_cover": 5000,
        "extra_cover_rule": "100,1.5,1.5",
        "icon_url": "http://test-static.npe.auspost.com.au/api/images/pac/regular_post_box.png",
        "description": "Based on the size and weight you've entered",
        "details": "Check our ",
        "delivery_time": "Delivered in up to 3 business days",
        "ui_display_order": 1,
        "options": {
          "option": [
            {

AJAX电话:

$.ajax({
            type: 'POST',
            dataType: 'JSON',
            url: 'AusPostDomestic.php',
            data: {toPostcode: toPostcodeValue, parcelLengthInCMs: parcelLengthInCMsValue, parcelHeighthInCMs: parcelHeighthInCMsValue, parcelWidthInCMs: parcelWidthInCMsValue, parcelWeightInKGs: parcelWeightInKGsValue},
            success: function(data) {
                //console.log(data);
                var obj = JSON.parse(data);
                $('#auspostresult').html(obj.services.service[0].code);
            }

1 个答案:

答案 0 :(得分:2)

您已经添加了数据类型为json,无需再次解析它。因此,从成功回调函数中删除行var obj = JSON.parse(data);

$.ajax({
  type: 'POST',
  dataType: 'JSON',
  url: 'AusPostDomestic.php',
  data: {
    toPostcode: toPostcodeValue,
    parcelLengthInCMs: parcelLengthInCMsValue,
    parcelHeighthInCMs: parcelHeighthInCMsValue,
    parcelWidthInCMs: parcelWidthInCMsValue,
    parcelWeightInKGs: parcelWeightInKGsValue
  },
  success: function(obj) {
    //console.log(data);
    $('#auspostresult').html(obj.services.service[0].code);
  }
});

Api Doc:http://api.jquery.com/jquery.ajax/