在angularjs中将字符串转换为对象时出错

时间:2016-03-09 10:52:30

标签: javascript angularjs ajax

我有以下字符串,我从ajax响应中获取:

[{
    id: "Abc",
    name: "ABCDD",
    color: "rgba(203,170,92,0.6)",
    div_class: "hotel_name"
}, {
    id: '136',
    name: 'PBss'
} ]

当我在变量中静态传递它然后它工作,但如果我从ajax请求返回相同,然后在变量中使用它然后它不起作用。我使用了以下代码:

不工作代码:

$http.post(urls)
        .success(function (response) {
            var x = JSON.parse(response);
            $scope.data = x;

        }).error(function (data, status, headers, config) {
            console.log('error');
        });

工作代码:

$http.post(urls)
        .success(function (response) {
            var x =  [{
                id: "Abc",
                name: "ABCDD",
                color: "rgba(203,170,92,0.6)",
                div_class: "hotel_name"
            }, {
                id: '136',
                name: 'PBss'
            } ];
            $scope.data = x;

        }).error(function (data, status, headers, config) {
            console.log('error');
        });

我无法找到问题的原因,请帮忙。 提前谢谢。

5 个答案:

答案 0 :(得分:0)

可能结果已经是JSON format.try而没有解析为JSON

var x = response;

答案 1 :(得分:0)

代码中的responseObject。您无法在对象上使用JSON.parseJSON.parse需要valid JSON string作为输入。

Angular会为您提供已解析的响应版本。所以你需要的只是

$scope.data = response.data;

在您的.success回调中。 :)

答案 2 :(得分:0)

 var x=[];
  x=response;
 $scope.data=x;

并将js代码更改为此

   $http.post(urls)
    .success(function (data1, status, headers, config) {
       var x=[]; 
        x = data1;
        $scope.data = x;

    }).error(function (data1, status, headers, config) {
        console.log('error');
    });

答案 3 :(得分:0)

你的意思是什么不起作用? A.您是否收到错误或者不是您想要的格式?

在你尝试JSON.parse()的那个片段上,当我们从服务器发送 json string 时我们使用解析,你发送 json string 吗? 换句话说,你最后在你的php文件json_encode()上使用了吗?

echo json_encode($result); //that converts object to json string ,and we get it from the client

然后在success我们解析对象:

$http.post(urls)
        .success(function (response) {
            var x = JSON.parse(response);
            $scope.data = x;

        }).error(function (data, status, headers, config) {
            console.log('error');
        });

更新

从服务器返回的正确json字符串应该是这样的:

["{\"id\": \"plazabeach\",\"name\": \"DDD\",\"color\": \"rgba(203,170,92,0.6 )\",\"div_class\": \"hotel_name\"}, {\"id\": \"136\",\"name\": \"PBss\"}"]

您可以在Chrome控制台上查看它:JSON.parse(此处所有字符串);

答案 4 :(得分:0)

如果我没有错,那么问题在于您的JSON数据。

[{
    id: "Abc",
    name: "ABCDD",
    color: "rgba(203,170,92,0.6)",
    div_class: "hotel_name"
}, {
    id: '136',//<-- This single quote characters is illegal. JSON specification states that only double quotes are allowed.
    name: 'PBss'//<-- This single quote characters is illegal. JSON specification states that only double quotes are allowed.
} ]

你能试试吗

var x = JSON.parse(JSON.stringify((response)));

我认为应该解决它!