jquery - 如何从 ajax 返回的 HTML 访问 json 数据?

标签 jquery ajax

我正在尝试从返回 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/

相关文章:

javascript - 获取类型错误 : invalid 'in' operand obj while fetching data using ajax

javascript - 根据要求实例化变量并编译 sass/less 文件

ajax - 在 jquery-ajax 函数之后提交

javascript - 在多个输入文件元素上添加事件监听器

javascript - 客户端或服务器正在删除变音符号

javascript - 如何使用 Ajax 从 Django 捕获 PermissionDenied(403)?

javascript - Reveal-modal 出现后如何调用函数

jquery - 将 jQuery delay() 与 css() 结合使用

javascript - Javascript/Ajax 中的 HTTP HEAD 请求?

ajax - AngularJS - 使用 $http 时是否需要 $scope.$apply