简体   繁体   English

使用$ .ajax返回HTML并将其转换为JavaScript数组

[英]Using $.ajax to return HTML & turn it into JavaScript array

var urlArray = window.location.pathname.split("/"),
    idFromUrl = urlArray[2],
    dataPath = "/bulletins/" + idFromUrl + "/data";

$.ajax({
    url: dataPath,
    type: "get",
    dataType: "html",
    success: function (data) {
        var dataObj = data.replace(/"/g, '"');

        console.log(dataObj);
    }
});

I'm grabbing the contents of an HTML page, and the contents on that page is super simple. 我正在抓取HTML页面的内容,该页面上的内容非常简单。 It's just an "array", although it's plain text so when it returns, JavaScript is treating it as a string instead of an array. 它只是一个“数组”,尽管它是纯文本,所以当返回时,JavaScript会将其视为字符串而不是数组。 This is all that's on that HTML page: 这就是该HTML页面上的所有内容:

[{"sermontitle":"test","welcome":"test","_id":"52e7f0a15f85b214f1000001"}]

Without replace the " 无需替换" 's, a console.log spits out [{"sermontitle":"test","welcome":"test","_id":"52e7f0a15f85b214f1000001"}] ,则console.log弹出[{"sermontitle":"test","welcome":"test","_id":"52e7f0a15f85b214f1000001"}]

So my question is, how can I turn that HTML string (that's already in "array" form) into an actual array? 所以我的问题是,如何将HTML字符串(已经以“数组”形式存在)转换为实际数组?

您可以使用JSON.parse

JSON.parse(dataObj);

Change "dataType" to "json" and it will convert it for you: 将“ dataType”更改为“ json”,它将为您转换:

var urlArray = window.location.pathname.split("/"),
    idFromUrl = urlArray[2],
    dataPath = "/bulletins/" + idFromUrl + "/data";

$.ajax({
    url: dataPath,
    type: "get",
    dataType: "json",
    success: function (data) {
        console.log(data);
    }
});

If it is returning the " 如果返回" instead of " , then I would change the AJAX return page to make sure it is doing a proper JSON response. 而不是" ,那么我将更改AJAX返回页面以确保它正在执行正确的JSON响应。

您可以将返回的HTML片段解析为JSON:

JSON.parse(dataObj);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM