2016-11-10 75 views
0

使用方法POST时收到此错误。请帮帮我。未捕获的语法错误意外的令牌{在JSON中

angular_min.js:114 SyntaxError: Unexpected token { in JSON at position 71 
    at JSON.parse (<anonymous>) 
    at wc (angular_min.js:16) 
    at cc (angular_min.js:88) 
    at angular_min.js:89 
    at n (angular_min.js:7) 
    at hd (angular_min.js:89) 
    at c (angular_min.js:91) 
    at angular_min.js:126 
    at m.$eval (angular_min.js:141) 
    at m.$digest (angular_min.js:138) 

我的代码: VAR JSON = {PARAMETER_NAME: “量”, “PARAMETER_VALUE”:$ scope.it.amount};

  var arr=[]; 
     arr.push(json); 
     $scope.object={formula:$scope.it.formula_saving_point}; 
     $scope.companyTemp={company_id:com_id}; 
     var url = API_URL + "cumulative_point_formula";  
     var cmd = "check_formula"; 
     var jsonFinal = JSON.stringify({json_parameter: JSON.parse(JSON.stringify(arr)), 
      company: JSON.parse(JSON.stringify($scope.companyTemp)), 
      cumulative_point_formula: JSON.parse(JSON.stringify($scope.object))}); 

此日志jsonFinal

{"json_parameter":[{"parameter_name":"amount","parameter_value":"111111111"}],"company":{"company_id":40743},"cumulative_point_formula":{"formula":"amount/10000"}} 

这是POST方法:

$http({ 
       method: 'POST', 
       url: url, 
       data: $.param({cm: cmd, dt: jsonFinal}), 
       headers: {'Content-Type': 'application/x-www-form-urlencoded'} 
      }).success(function (response) { 
       console.log("success"); 
}); 

如何修复这个bug?

+0

你是否故意在这个问题中重复你的代码? – Claies

+1

'JSON.parse(JSON.stringify($ scope.companyTemp))'呃...为什么? –

+0

@Derek朕会功夫:老派克隆对象的方式。在很多浏览器中,它仍然是最快的方法 – slebetman

回答

0

如果你仔细看看你的错误它源于JSON.parse,而不是$ HTTP。我相信是由该行

var jsonFinal = JSON.stringify({json_parameter: JSON.parse(JSON.stringify(arr)), 
    company: JSON.parse(JSON.stringify($scope.companyTemp)), 
    cumulative_point_formula: JSON.parse(JSON.stringify($scope.object))}); 

,其中该块这里代码非常冗余导致此错误:

JSON.parse(JSON.stringify($scope.companyTemp)) 

字符串化>解析会导致同$范围。 companyTemp以及其他,并且与此相同:

var jsonFinal = JSON.stringify({ 
     json_parameter: arr, 
     company: $scope.companyTemp, 
     cumulative_point_formula: $scope.object 
    }); 

JSON.parse JSON字符串转换为有效的JavaScript对象

JSON.stringify JavaScript对象转换为字符串

如果仍然产生一个错误,我相信这三个改编之一,$ scope.companyTemp$ scope.object具有无效值。

希望可以帮到

+0

嗨Preenz,我知道了,我尝试你的方式,但我解决它。我再次收到“SyntaxError:Unexpected token {在位置71的JSON中”。但我console.log jsonFinal并在POSTMAN中测试它。它运行。结果是:[ { “结果”:“1” } ] 可以再次帮助我吗? – John

+0

我不能完全猜测这些变量里面有什么,但一定要检查这些是否有对象或数组值,如果其中一个是**字符串**,** JSON.stringify **会炸毁。检查出这些变量** arr **,** $ scope.companyTemp **,** $ scope.object **,** $ scope.it.formula_saving_point **,** com_id ** – masterpreenz

+0

哦,我知道并且解决它。非常感谢你。 – John

相关问题