2

我正在尝试从返回 html 和 json 的 Ajax 调用中检索 json 项目数据。我下面的 javascript 返回一条成功消息,这很有帮助;我只是不确定如何访问数据。我正在尝试newPrice从此响应中访问:

Data Loaded: <pre>Array
(
[point] => 86
[claimId] => 3594
[type] => yeh
)
</pre>{"data":{"newPrice":88,"lockedInPrice":86},"errors":[],"success":true,"code":200}

我的代码如下。我特别想只返回 newPrice 值:

var newData = $.ajax({ 
    type: "POST",
    url: takeurl,
    dataType: "html",
    data: { point: point, claimId: id, type: val }
    })
    .success(function(data) { 
        alert("Data Loaded: " + data);
        //newPrice = data.newPrice; -- returned undefined?
        console.log(newPrice);
        })

    .error(function() { alert("not yet"); })
    .complete(function(data) { 
        console.log('complete 1' );
    });

// Set another completion function for the request above
newData.complete(function(data){ 
    console.log("second complete" );
    });


return false;
 });

谢谢!

4

3 回答 3

4

您的响应中似乎同时包含 HTML 和 JSON。通常响应只是 JSON,并以内容类型 application/JSON 进行响应。尽管可以使用响应,但这有点不正统。

您可以使用 substring 和 indexof 删除 HTML 部分“”,然后使用 JSON 创建一个 javascript 对象。

var data = "<pre>Array\n(\n[point] => 86\n[claimId] => 3594\n[type] => yeh\n)\n</pre>{\"data\":{\"newPrice\":88,\"lockedInPrice\":86},\"errors\":[],\"success\":true,\"code\":200}";

alert("Data Loaded: " + data);
var n = data.indexOf("</pre>{");
data = data.substring(n+6);
var result = JSON.parse(data);
alert("JSON.newPrice:"+result.data.newPrice);

JSON.parse() 方法用于将 JSON 字符串转换为 JSON 对象。

于 2013-04-12T20:38:43.983 回答
0

如果您想以 JSON 格式访问响应,则它必须以application/json内容类型返回,并且看起来像一个有效的 JavaScript 普通对象。还设置了dataType对 的jQuery.ajax调用json

于 2013-04-12T20:39:02.963 回答
0

为了避免在控制器的 Json 响应中获取带有“pre”标签的 HTML,请使用以下代码片段。

var result= objectData;
return Json(result, "text/html");
于 2015-12-13T06:52:51.683 回答