我正在尝试从返回 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;
});
谢谢!
最佳答案
您的响应中似乎同时包含 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对象。
关于jquery - 如何从 ajax 返回的 HTML 访问 json 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15980387/